0

Why this code give -91value

int Y=26789; byte b=(byte) Y; System.out.println(b);

25th May 2020, 7:48 AM
EMma♊
3 Answers
+ 2
Cause byte is 8 bit and only has 256 values and 26789%256=165. But 8 bit represent the range of -128 to 127 so you need to calc 165 - 256 = -91
25th May 2020, 8:04 AM
Jnn
Jnn - avatar
+ 1
Byte in Java is in 2nd-complement. In binary 165 is 10100101. Cause the most significant bit is 1 it is a negative number. To get the absolute value you need to switch every bit and add 1: 01011010 + 1 = 01011011 = 64 + 16 + 8 + 2+ 1= 91
25th May 2020, 8:10 AM
Jnn
Jnn - avatar
+ 1
Thank you 🙂🙂
25th May 2020, 8:12 AM
EMma♊