tags:

views:

923

answers:

5

An integer's max value in Java is 2147483647, since Java integers are signed, right?

0xff000000 has a numeric value of 4278190080.

Yet I see Java code like this:

int ALPHA_MASK = 0xff000000;

Can anyone enlighten me please?

+1  A: 

the extra bit is for the sign

Java ints are twos complement

Jimmy
+16  A: 

The high bit is a sign bit. Setting it denotes a negative number: -16777216.

Java, like most languages, stores signed numbers in 2's complement form. In this case, subtracting 231, or 2147483648 from 0x7F000000, or 2130706432, yields -16777216.

erickson
A: 

ints are signed in Java.

Uri
+22  A: 

Just an addition to erickson's answer:

As he said, signed integers are stored as two's complements to their respective positive value on most computer architectures.

That is, the whole 2^32 possible values are devided into two areas: one for positive values starting with a 0-bit and the one for negative values starting with a 1.

Now, imagine that we're limited to 3-bit numbers:

     000
  111   001 
110       010
  101   011  
     100

001, 010 and 011 are the only possible positive numbers whereas 111, 110 and 101 are their respective negative counterparts. 000 is zero, obviously, and 100 is the lowest negative number of all which doesn't have a positive counterpart.

     000      (0)
  111   001   (-1 / 1)
110       010 (-2 / 2)
  101   011   (-3 / 3)
     100      (-4)

You also see that you can get the bit pattern of -1 (111) by negating 1 (001) and adding 1 (001) to it: 001 (= 1) -> 110 + 001 -> 111 (= -1)

Coming back to your question:

0xff000000 = 1111 1111 0000 0000 0000 0000 0000 0000

We don't have to add further zeros in front of it as we already reached the maximum of 32 bits. Also, it's obviously a negative number (as it's starting with a 1-bit), so we're now going to calculate its absolute value / positive counterpart:

          1111 1111 0000 0000 0000 0000 0000 0000

Calculating the two's complement:

          0000 0000 1111 1111 1111 1111 1111 1111
        + 0000 0000 0000 0000 0000 0000 0000 0001

        = 0000 0001 0000 0000 0000 0000 0000 0000
        = 16777216

Therefore, 0xff000000 = -16777216

codethief
@Kitsune (and/or anyone who doesn't already know this): This is a good explanation. It might take a few times to read it but I recommend you read it through until it really makes sense.
Bill K
thanks a lot! I grok it now
kitsune
Excellent visual
Chris Ballance
+4  A: 

Something probably worth pointing out - this code is not meant to be used as an integer with a numerical value; The purpose is as a bitmask to filter the alpha channel out of a 32 bit color value. This variable really shouldn't even be thought of as a number, just as a binary mask with the high 8 bits turned on.

Chris Shaffer