0

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?

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
Shivam Paw
  • 203
  • 3
  • 14
  • If I convert your hexString using [this accepted method here](http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java) and feed the byte-array to `new BigInteger(bytes).intValue()` I also get -60 in return – Roman Vottner Jun 13 '15 at 00:05
  • Although you already found an answer, for completeness reasons you could also pass the hex-string to [BigInteger](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html) directly and convert it to long value using this code: `new BigInteger("FFFFFFC4", 16).longValue()` - this will produce a value of `4294967236`. – Roman Vottner Jun 13 '15 at 00:17

1 Answers1

0

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;
}
Mike Laren
  • 8,028
  • 17
  • 51
  • 70