aspose file tools*
The moose likes Java in General and the fly likes Overflow and Underflow Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Overflow and Underflow" Watch "Overflow and Underflow" New topic
Author

Overflow and Underflow

Drew Lane
Ranch Hand

Joined: May 13, 2001
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

Joined: Jul 08, 2003
Posts: 24166
    
  30

You're describing an unsigned 16-bit integer; Java's "char" is such a beast, if used carefully.


[Jess in Action][AskingGoodQuestions]
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
you can use % operator.
Surasak Leenapongpanit
Ranch Hand

Joined: May 10, 2002
Posts: 341
As same as chi Lin's method:
Number = Number % 65536
if Number < 0
Number += 65536
chi Lin
Ranch Hand

Joined: Aug 24, 2001
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

Joined: May 13, 2001
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

Joined: Aug 24, 2001
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

Joined: Aug 24, 2001
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

Joined: May 13, 2001
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overflow and Underflow
 
Similar Threads
Stacks
exception related
How to calculate number of days between two Timestamp
How to calculate number of days between two Timestamp
integer overflow