Just had a small "doh" moment, and thought I would write it here so it perhaps helps people avoid the same mistake In a program, I want to play around with bits and stuff. So, naturally I prefer hex notation. I initialized a variable like this:
Knowing that the variable is big enough to hold that value. To my surprise, upon printing the value it displayed -252645136 instead of the expected positive number.
The reason is of course that number literals are interpreted as int values...so to correct this I changed the above to
That was a nasty little surprise! Hope this helps someone ;)
EDIT: why is the number displayed red in the first piece of code? Does this forum check values???
The real problem is that hex literals support unsigned numbers. 0xf0f0f0f0 is greater than Integer.MAX_VALUE which is 0x7fffffff, so it is converted into binary as 1111_0000_1111_0000_1111_0000_1111_0000, which is a negative number.
Joined: Feb 02, 2009
Yes I know that, its why I used long in the first place. Long can hold that value without problem, but the compiler interprets the value as an integer and thus, as you said, a negative number. So using the notation with "L" at the end is really required then.