Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing bitwise not on a byte

I am attempting to perform a bitwise not on a byte, like this:

byte b = 125;
byte notb = ~b; // Error here

This doesn't work because the not operator only works with integer types. I can do this, and this seems to work:

byte b = 125;
byte notb = (byte)((~b) & 255);

This seems to work because its not'ing the number, then flipping all bits after the 8th bit to 0, then casting it to a byte. What I am wondering is if there is a better way to do this or a simpler way that I am just overlooking?

like image 775
Icemanind Avatar asked May 04 '14 07:05

Icemanind


1 Answers

It doesn't look like Lynx is planning on updating his answer, so for future reference, bitwise operators work fine on byte. They just return an int, which is not assignable to a variable of type byte. You only need one cast here:

byte notb = (byte)~b;
like image 118
Asad Saeeduddin Avatar answered Oct 14 '22 10:10

Asad Saeeduddin