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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With