Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

hex - Why is Java able to store 0xff000000 as an int?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 split up into two sets: one for positive values starting with a 0-bit and one for negative values starting with a 1.

Now, imagine that we're limited to 3-bit numbers. Let's arrange them in a funny way that'll make sense in a second:

     000
  111   001 
110       010
  101   011  
     100  

You see that all numbers on the left-hand side start with a 1-bit whereas on the right-hand side they start with a 0. By our earlier decision to declare the former as negative and the latter as positive, we see that 001, 010 and 011 are the only possible positive numbers whereas 111, 110 and 101 are their respective negative counterparts.

Now what do we do with the two numbers that are at the top and the bottom, respectively? 000 should be zero, obviously, and 100 will be the lowest negative number of all which doesn't have a positive counterpart. To summarize:

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

You might notice 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:

This means, we'll take the two's complement of

1111 1111 0000 0000 0000 0000 0000 0000

which is

0000 0000 1111 1111 1111 1111 1111 1111

Then we add

0000 0000 0000 0000 0000 0000 0000 0001

and obtain

0000 0001 0000 0000 0000 0000 0000 0000 = 16777216

Therefore, 0xff000000 = -16777216.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...