java - Behavior of bitwise xor using binary literals -


i'm curious know happens on bitwise comparison using binary literals. came across following thing:

byte b1 = (new byte("1")).bytevalue();  // check bit representation system.out.println(string.format("%8s", integer.tobinarystring(b1 & 0xff)).replace(' ', '0')); // output: 00000001  system.out.println(b1 ^ 0b00000001); // output: 0 

so behaves expected, xor comparison equals 0. when trying same negative number won't work:

byte b2 = (new byte("-1")).bytevalue();  // check bit representation system.out.println(string.format("%8s", integer.tobinarystring(b2 & 0xff)).replace(' ', '0')); // output: 11111111  system.out.println(b2 ^ 0b11111111); // output: -256 

i have expected last xor comparison equals 0. case if explicit cast of binary literal byte:

byte b2 = (new byte("-1")).bytevalue();  // check bit representation system.out.println(string.format("%8s", integer.tobinarystring(b2 & 0xff)).replace(' ', '0')); // output: 11111111  system.out.println(b2 ^ (byte)0b11111111); // output: 0 

for me looks before xor comparison both b1 , 0b11111111 have same bit representation if casted int (or else) xor should still equal 0. how come result of -256 11111111 11111111 11111111 00000000 in binary representation? why have explicit cast byte in order obtain 0?

when use b1 ^ 0b11111111 xor between byte int byte 8 bit variable while int 32 bit number. so, did is: b1 ^ 0b(00000000 00000000 00000000 11111111) when use xor between byte (with additional 1s before use int. 1s because negetive number. if positive 0s) , int result integer , in case, -256.

when cast integer byte using xor between 2 bytes , result byte.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -