Question:
I have just read a packet of data into a byte array from a socket. At offsets 5-8, 9-12, and 13-16 are binary integers. How can I get them into Java int variables?
Answer:
The recommended way of doing this is to use java.io.ObjectInputStreamand its readInt() method. However, there are cases where you will wantto deal with bytes directly, such as when you are converting little-endianintegers to big-endian integers. The easiest way to address how to do thisis simply to give an example. The following program takes four bytesin big-endian order and turns them into a Java integer:
public final class bytesToInt { public static final void main(String[] args) { byte[] bytes; int result, bitmask; bytes = new byte[4]; bytes[0] = 1; // 00000001 bytes[1] = 2; // 00000010 bytes[2] = 3; // 00000011 bytes[3] = 4; // 00000100 result = 0; result |= ((0xff & bytes[0]) << 24); result |= ((0xff & bytes[1]) << 16); result |= ((0xff & bytes[2]) << 8); result |= (0xff & bytes[3]); System.out.println("int : " + result); System.out.print("bits: "); // Print the individual bits to show they were set correctly bitmask = 0x80000000; for(int i=0; i < 32; i++) { if((result & bitmask) == 0) System.out.print('0'); else System.out.print('1'); bitmask >>>= 1; } System.out.println(); }}