Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Conversion between int and byte[]
Conversion between int and byte[]

1.int to byte[] low byte first (little endian)

public static byte[] toLH(int n) {

? byte[] b = new byte[4];

? b[0] = (byte) (n & 0xff);

? b[1] = (byte) (n >> 8 & 0xff);

? b[2] = (byte) (n >> 16 & 0xff);

? b[3] = (byte) (n >> 24 & 0xff);

? return b;

}

2.?int is converted to byte[] with high byte first (high byte first) Byte order)

public static byte[] toHH(int n) {

? byte[] b = new byte[4];

? b [3] = (byte) (n & 0xff);

? b[2] = (byte) (n >> 8 & 0xff);

? b[1] = (byte) (n >> 16 & 0xff);

? b[0] = (byte) (n >> 24 & 0xff);

? return b;< /p>

}

3.?byte[] to int, low byte first (little endian)

public int toInt(byte[] b){

int res = 0;

for(int i=0;i

res += (b[i] & 0xff) << (i*8);

}

return res;

}

4.byte[] transfer int high byte first (big endian)

public static int toInt(byte[] b){

int res = 0;

for (int i=0;i

res += (b[i] & 0xff) << ((3-i)*8);

< p> }

return res;

}