Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Bitwise Xor of bytes  RSS feed

 
Ernie Mcracken
Ranch Hand
Posts: 33
Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is puzzling me,




If I use the bitwise Xor of two bytes why do I get the compile time error




I guess this means that one ^ two returns an int, but I don't understand why.

Thanks

 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's one of the gotchas of Java. All integer operators result in either an int or a long. So any operator acting on primitives "smaller than" int returns an int.

E.g.
short + short = int
byte * short = int
byte ^ byte = int


I'm not entirely sure why it was designed like that, but there'll probably be someone along to explain it .

The result is, you need to write:
 
Ernie Mcracken
Ranch Hand
Posts: 33
Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is rather strange.
Thank you!
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And the operators += -= *= /= %= &= ^= |= <<= >>= >>>= have a build it cast.
So byte a = 5; a += 5; is valid.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!