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

Range of bitwise operators

 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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?

Thanks
 
Bupjae Lee
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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.
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks very much
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic