Hi,
I want to combine 2 different bytes into an integer, so that 1 byte
will be to the left of the second byte.
example:
byte[2] b;
b[0] = 0xE5;
b[1] = 0x35;
I want to get the unsigned number of 0xE535 (=58677), so I did:
int num = (b[0] << 8) | b[1];
But I got the negative number -6859.
How can I get the desired result (58677)?
-thanks, Eli
eli.hen@gmail.com - 18 Dec 2005 06:28 GMT
Found the solution: ;-)
int num = (((int)b[0] & 0xFF) << 8) | ((int)b[1] & 0xFF)
Roedy Green - 18 Dec 2005 11:03 GMT
>int num = (((int)b[0] & 0xFF) << 8) | ((int)b[1] & 0xFF)
the int casts are not needed. & 0xff promotes a byte to int.

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 18 Dec 2005 11:03 GMT
>example:
> byte[2] b;
[quoted text clipped - 5 lines]
>
>How can I get the desired result (58677)?
see http://mindprod.com/jgloss/endian.html
http://mindprod.com/jgloss/unsigned.html

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.