Question

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?

Was it helpful?

Solution

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;

OTHER TIPS

This is basically better than the one that you wrote because it is more clear. I have read some topics about this thing, but it seems like you can't really use a bitwise not on a byte.

byte b = 125;
byte notb= (byte)~b; // result is 130

This will work

byte b = 125;
byte notb = (byte)~(int)b;

This is casting b to int and then doing ~ and casting it back to byte.

I've verified result. Both your and my code outputs 130.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top