Question

I have a byte array -

byte[] byteArr = new byte[] { (byte)0x00 , (byte)0xF0 , (byte)0x03 };

I am just getting each one,

Integer byte1 = Integer.valueOf(byteArr[0]);
Integer byte2 = Integer.valueOf(byteArr[1]);
Integer byte3 = Integer.valueOf(byteArr[2]);

String pgnString = byte1.toString() + byte2.toString() + byte3.toString();

And my output is: 0-163

But I can see the correct output should be: 61443

Link--- http://www.binaryhexconverter.com/hex-to-decimal-converter

Was it helpful?

Solution

Thats because bytes are signed. (byte)0xF0 is actually the same as (byte)-16.

To convert as unsigned quantity you can mask the lower 8 bits:

int byte1 = byteArr[0] & 0xff;
int byte2 = byteArr[1] & 0xff;
int byte3 = byteArr[2] & 0xff;

String pgnString = String.valueOf(byte1 * 0x10000 + byte2 * 0x100 + byte3);

OTHER TIPS

If you don't want to go through them one at a time, you can use ByteBuffer to convert to another base.

byte[] byteArr = new byte[] { (byte)0x00 , (byte)0x00 , (byte)0xF0 , (byte)0x03 };
int value = ByteBuffer.wrap(byteArr).getInt();
// value = 61443

Note: the byte[] must have a length of 4 (or call getInt() for each 4 byte part).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top