0

I have a question about how two's complement works when casting an int to a byte. For instance, when casting an int whose value is between 127 and 256, I get negative values, and I'd like to understand how. I get that the high-order bits get thrown out, so anything between 256 and 512 results in the byte variable holding the int value minus 256; but I'm curious about how to work out the negative values in binary.

For instance, I'm curious about how the following piece of code works:

int i = 140;    
byte b = (byte) i;    
System.out.println(b); // outputs -116

140 is 10001100 in binary, and in two's complement binary from what I gather. In binary, how does 10001100 become the two's complement binary value necessary to output -116?

mishar
  • 89
  • 6
  • 1
    Possible duplicate of [What is “2's Complement”?](https://stackoverflow.com/questions/1049722/what-is-2s-complement) – Tim Biegeleisen Sep 29 '19 at 05:07
  • Well, I've looked at what is 2's complement, but I haven't found anything about how it relates to casting. I've found a janky way to do it, but I'm not sure. 140 is 10001100 in binary. Casting that to a byte, it's too large of a value. So, performing 2's complement on all but the highest-order bit yields 1110100, which is -116. But I'm not sure why this is what's performed, or even if this is what's performed. It merely seems to work in this instance. – mishar Sep 29 '19 at 05:19

0 Answers0