Icemanind
Icemanind

Reputation: 48736

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?

Upvotes: 7

Views: 4573

Answers (3)

Lynx
Lynx

Reputation: 506

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

Upvotes: 1

user1726343
user1726343

Reputation:

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;

Upvotes: 6

Amit Joki
Amit Joki

Reputation: 59292

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.

Upvotes: 0

Related Questions