I have a hexBinary of 4 bytes as follows:
FFFFFFC4
It should return something big but the following function just gives -60:
public static int byteArrayToInt(byte[] b)
{
return b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}
Why it doesn't work? Am I doing something wrong?
The primitive type int
is 32-bits long and the most significative bit is the sign. The value FFFFFFC4
has the MSB set to 1
, which represents a negative number.
You can get "something big" by using long
instead of int
:
public static long byteArrayToInt(byte[] b)
{
return (((long) b[3]) & 0xFF) |
(((long) b[2]) & 0xFF) << 8 |
(((long) b[1]) & 0xFF) << 16 |
(((long) b[0]) & 0xFF) << 24;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.