Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overflow and Underflow

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to perform an overflow if a variable is greater than 65535 so that 65536 equals 0.
Likewise, if the number is less than 0 I need to underflow so that -1 equals 65535.
How is this performed in Java?
Thanks,
Drew
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're describing an unsigned 16-bit integer; Java's "char" is such a beast, if used carefully.
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can use % operator.
 
Surasak Leenapongpanit
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As same as chi Lin's method:
Number = Number % 65536
if Number < 0
Number += 65536
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
surasak,
You read my mind , further more, we can make the cutoff (65535)
as another parmeter to make the whole thing more flexible.
 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would it also be possible to do this with some kind of bit shift?
Or could I extract the last 16 bits?
Not sure what the Java syntax is, however. (?)
Drew
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use & operator to bitwise AND the number with mask 0xFFFF
to get the last 16 bits.
then use Integer.toBinaryString(int i) to get the result in binary form.
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
one more note,
to get full display of the 16 bits, you may need to do
some padding so 2 (10) become 0000000000000010.
 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, it looks like this puppy will take care of it:
int x = y & 0xffff;
Wow...that was easy.
You are smart.
Thanks,
Drew
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic