Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Overflow and Underflow

Drew Lane
Ranch Hand
Posts: 296
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
Posts: 24212
35
You're describing an unsigned 16-bit integer; Java's "char" is such a beast, if used carefully.

chi Lin
Ranch Hand
Posts: 348
you can use % operator.

Surasak Leenapongpanit
Ranch Hand
Posts: 341
As same as chi Lin's method:
Number = Number % 65536
if Number < 0
Number += 65536

chi Lin
Ranch Hand
Posts: 348
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
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
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
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
So, it looks like this puppy will take care of it:
int x = y & 0xffff;
Wow...that was easy.
You are smart.
Thanks,
Drew