How can I convert byte array block of 4 to integer number.
If we had these bytes of file in Hex Editor:
CB 01 00 00
The hexidecimal value of this block is DWORD of 000001CB
= 1CB
hex = 459
in decimal.
How can I convert any byte array (byte[]
) block (of four bytes) to integer (decimal value of block)?
I am looking for method like this:
public int getDecimalFromBlock( byte... bytes ) {
for ( byte b: bytes ) {
// do the magic
}
}
Where parameter byte in number between byte range (-127, 127).
Let's assume that your byte order is Little Endian (based on your post), and so the decoding will be
int value = ((data[0]&0xff) |
((data[1]&0xff)<<8) |
((data[2]&0xff)<<16) |
((data[3]&0xff)<<24));
If the order is Big endian, it will look something like:
int value = ((data[3]&0xff) |
((data[2]&0xff)<<8) |
((data[1]&0xff)<<16) |
((data[0]&0xff)<<24));
In both cases the variant "data" is a "byte[]"
byte[] data = new byte[] {(byte)0xcb, 0x01, 0x00, 0x00};
Update to the edited request.
I assume you may have problems with 0xcb as interpreted as negative value, this may be fixed by applying a &
operator
Complete code with test case
public class DecimalTest
{
public static int getDecimalFromBlock( byte... bytes ) {
int result = 0;
for(int i=0; i<bytes.length; i++)
{
result = result | (bytes[i] & 0xff)<<(i*8);
}
return result;
}
public static void main(String[] args) throws IOException
{
System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb}));
System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01}));
System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01, 0x00}));
System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01, 0x00, 0x00}));
System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01, 0x00, 0x00, 0x00}));
}
}