バイナリ リテラルを使用したビットごとの比較で実際に何が起こるか知りたいです。私はちょうど次のことに出くわしました:
byte b1 = (new Byte("1")).byteValue();
// check the bit representation
System.out.println(String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0'));
// output: 00000001
System.out.println(b1 ^ 0b00000001);
// output: 0
したがって、すべてが期待どおりに動作し、xor
比較は等しいです0
。ただし、負の数で同じことをしようとすると、うまくいきません:
byte b2 = (new Byte("-1")).byteValue();
// check the bit representation
System.out.println(String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0'));
// output: 11111111
System.out.println(b2 ^ 0b11111111);
// output: -256
xor
最後の比較も等しいと予想していました0
。ただし、これは、バイナリリテラルを明示的にキャストした場合にのみ当てはまりbyte
ます。
byte b2 = (new Byte("-1")).byteValue();
// check the bit representation
System.out.println(String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0'));
// output: 11111111
System.out.println(b2 ^ (byte)0b11111111);
// output: 0
xor
私にとっては、比較前は同じように見え、同じビット表現b1
を0b11111111
持っているので、それらがint
(または他の何かに)キャストされたとしても、xor
は 等しいはず0
です。どのようにして結果が-256
211111111 11111111 11111111 00000000
進表現になるのでしょうか? byte
を取得するために明示的なキャストを行う必要があるのはなぜ0
ですか?