Java中byte类型强制转换140得到-116的原理解析
Let's walk through this step by step—this is all about how Java handles signed 8-bit integers (byte type) and integer overflow rules.
First, let's recap the basics:
- In Java, a
byteis a signed 8-bit integer stored using two's complement. Its valid range is from-128to127(inclusive). Any value outside this range will wrap around according to two's complement rules when cast tobyte.
Now let's break down what happens to 140 when you cast it to byte:
Convert 140 to 8-bit binary
The decimal value 140 translates to the 8-bit binary10001100. Sincebyteonly uses 8 bits, casting the 32-bitintvalue 140 tobytetells Java to discard all higher bits and keep only these 8 bits.Interpret the 8-bit binary as a signed two's complement number
In two's complement notation, the leftmost bit acts as the sign bit:- A
0means the number is positive - A
1means the number is negative
Our 8-bit value
10001100has a sign bit of1, so it represents a negative number. To find its decimal equivalent:- Flip all bits of
10001100to get the one's complement:01110011 - Add 1 to this value to get the positive magnitude:
01110100 - Convert this binary to decimal:
01110100equals 116 - Since the original sign bit was
1, the final value is-116
- A
A quicker way to calculate this is using modulo arithmetic:
The total range of an 8-bit signed integer is 256 (2^8). Any value above 127 wraps around by subtracting 256. So 140 - 256 = -116—same result!
Let's confirm with your code snippet:
public class DataTypes { public static void main(String args[]){ byte b = (byte)140; System.out.println(b); } }
When you run this, Java truncates the 32-bit int 140 to its 8-bit two's complement representation, then interprets that as the signed integer -116 and prints it.
内容的提问来源于stack exchange,提问作者Nishant sharma

