File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Range of bitwise operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Range of bitwise operators" Watch "Range of bitwise operators" New topic

Range of bitwise operators

Sol Mayer-Orn
Ranch Hand

Joined: Nov 13, 2002
Posts: 311

When using java bitwise operators (such as bitwise-and "|", bitwise-xor "^") , i have just noticed that *int* is returned, even if the operands are bytes or shorts.
For example:

Would anyone please happen to know the reason for this?
(Sure, you can cast the result later... but why do they return 'int' in the first place?)
I mean, when it comes to arithmetical plus (+) I can understand why byte+byte might yield a result larger than byte range (due to 'carry').
But when it comes to bitwise operators(and/or/xor) between 2 bytes, surely they can never yield anything larger than a byte? Or am I missing something in the spec?

Bupjae Lee
Ranch Hand

Joined: May 14, 2007
Posts: 107
In Java Virtual Machine, unfortunely, arithmetical operation only supports int, long, float, and double type, and bitwise operation only supports int and long type. It is mentioned in Java Language Specification and Java Virtual Machine Specification.
Sol Mayer-Orn
Ranch Hand

Joined: Nov 13, 2002
Posts: 311
Thanks for taking the time to read and reply

My question is: *why* did they decide on this spec?

Is there some clever mathematical justification, which i'm missing?

Or is it just some technical reason (like the fact most hardware was 32 bit, at the time)? Or some smarter technical problems, which I can't think of ?

Thanks again.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
[Sol Mam-Orn]: like the fact most hardware was 32 bit, at the time

I believe this was it, yes. Many operations require only a single processor instruction for a 4-bit int, and would require additional instructions to downcast the result to a smaller type and remove the excess bits. So they defined the language so that wouldn't be necessary most of the time.

"I'm not back." - Bill Harding, Twister
Sol Mayer-Orn
Ranch Hand

Joined: Nov 13, 2002
Posts: 311
thanks very much
I agree. Here's the link:
subject: Range of bitwise operators
It's not a secret anymore!