java - Bitwise AND operation with a signed byte -
here code:
int = 200; byte b = (byte) 200; system.out.println(b); system.out.println((short) (b)); system.out.println((b & 0xff)); system.out.println((short) (b & 0xff)); here output:
-56 -56 200 200 bitwise , 0xff shouldn't have changed in b, apparently have effect, why?
it has effect because 200 beyond maximum possible (signed) byte, 127. value assigned -56 because of overflow. significant byte, worth -128, set.
11001000 the first 2 output statements show -56 because of this, , fact casting short perform sign extension preserve negative values.
when perform & 0xff, 2 things happen. first, value promoted int, sign extension.
11111111 11111111 11111111 11001000 then, bit-and performed, keeping last 8 bits. here, 8th bit no longer -128, 128, 200 restored.
00000000 00000000 00000000 11001000 this occurs whether value casted short or not; short has 16 bits , can represent 200.
00000000 11001000
Comments
Post a Comment