You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中byte类型强制转换140得到-116的原理解析

Why (byte)140 equals -116 in Java?

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 byte is a signed 8-bit integer stored using two's complement. Its valid range is from -128 to 127 (inclusive). Any value outside this range will wrap around according to two's complement rules when cast to byte.

Now let's break down what happens to 140 when you cast it to byte:

  1. Convert 140 to 8-bit binary
    The decimal value 140 translates to the 8-bit binary 10001100. Since byte only uses 8 bits, casting the 32-bit int value 140 to byte tells Java to discard all higher bits and keep only these 8 bits.

  2. 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 0 means the number is positive
    • A 1 means the number is negative

    Our 8-bit value 10001100 has a sign bit of 1, so it represents a negative number. To find its decimal equivalent:

    • Flip all bits of 10001100 to get the one's complement: 01110011
    • Add 1 to this value to get the positive magnitude: 01110100
    • Convert this binary to decimal: 01110100 equals 116
    • Since the original sign bit was 1, the final value is -116

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:58:21