Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hex literals

 
D. Ogranos
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50241
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50241
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic