aspose file tools*
The moose likes Beginning Java and the fly likes Hex literals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Hex literals" Watch "Hex literals" New topic
Author

Hex literals

D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
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???
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

why is the number displayed red in the first piece of code? Does this forum check values???

No. I think that the red color means that value is a number. The parser doesn't interpret the second value as a number because of the trailling 'L', so it is displayed in black.


[My Blog]
All roads lead to JavaRanch
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
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.
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
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.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hex literals