Convert 4 bytes to int Convert 4 bytes to int java java

Convert 4 bytes to int


ByteBuffer has this capability, and is able to work with both little and big endian integers.

Consider this example:

//  read the file into a byte arrayFile file = new File("file.bin");FileInputStream fis = new FileInputStream(file);byte [] arr = new byte[(int)file.length()];fis.read(arr);//  create a byte buffer and wrap the arrayByteBuffer bb = ByteBuffer.wrap(arr);//  if the file uses little endian as apposed to network//  (big endian, Java's native) format,//  then set the byte order of the ByteBufferif(use_little_endian)    bb.order(ByteOrder.LITTLE_ENDIAN);//  read your integers using ByteBuffer's getInt().//  four bytes converted into an integer!System.out.println(bb.getInt());

Hope this helps.


If you have them already in a byte[] array, you can use:

int result = ByteBuffer.wrap(bytes).getInt();

source: here


You should put it into a function like this:

public static int toInt(byte[] bytes, int offset) {  int ret = 0;  for (int i=0; i<4 && i+offset<bytes.length; i++) {    ret <<= 8;    ret |= (int)bytes[i] & 0xFF;  }  return ret;}

Example:

byte[] bytes = new byte[]{-2, -4, -8, -16};System.out.println(Integer.toBinaryString(toInt(bytes, 0)));

Output:

11111110111111001111100011110000

This takes care of running out of bytes and correctly handling negative byte values.

I'm unaware of a standard function for doing this.

Issues to consider:

  1. Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and

  2. Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use readByte() repeatedly and not worry about it otherwise;

  3. Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.

to further elaborate on the point of buffering, consider the BufferedInputStream:

InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);

Now you have an InputStream that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.

Secondly you can also use DataInputStream:

InputStream in = new DataInputStream(new BufferedInputStream(                     new FileInputStream(file), 1024));byte b = in.readByte();

or even:

int i = in.readInt();

and not worry about constructing ints at all.