質問

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;

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top