Android Int to Byte Array Convert intToBytes(int x)

Here you can find the source of intToBytes(int x)

Description

int To Bytes

Declaration

public static byte[] intToBytes(int x) 

Method Source Code

//package com.java2s;

import java.nio.ByteBuffer;

public class Main {
    private static ByteBuffer int_buffer = ByteBuffer.allocate(4);

    public static byte[] intToBytes(int x) {
        int_buffer = ByteBuffer.allocate(4);
        int_buffer.putInt(x);
        return subByte(int_buffer.array(), -2);
    }//www.j  a  v  a 2s . co  m

    /**
     * @param data
     * @param start
     * @param end
     * @return
     */
    public static byte[] subByte(byte[] data, int start, int end) {
        int len = data.length;
        if (start >= len || end <= start || end < 1) {
            return null;
        }
        byte[] result = new byte[(end - start)];
        for (int i = start, j = 0; i < len; i++, j++) {
            if (i < end) {
                result[j] = data[i];
            } else {
                break;
            }
        }
        return result;
    }

    public static byte[] subByte(byte[] data, int start) {
        int len = data.length;
        if (start >= len) {
            return null;
        }
        if (start < 0) {
            start = len + start;
            if (start < 0) {
                return null;
            }
        }
        byte[] result = new byte[(len - start)];
        for (int i = start, j = 0; i < len; i++, j++) {
            result[j] = data[i];
        }
        return result;
    }
}

Related

  1. intToByteArray(int value)
  2. intToBytes(int i)
  3. intToBytes(int in)
  4. intToBytes(int n)
  5. intToBytes(int number)
  6. toBytes(int value)
  7. toBytes(int value, byte[] dest, int destPos)
  8. getBytes(int data)
  9. putInt(byte[] bb, int x, int index)