← 中文资源

简体中文版本

Integer 无符号口径解析与运算

用 parseUnsignedInt/divideUnsigned/compareUnsigned 在无符号语义下解析、做除法与比较:同一个位模式在两种口径下得到不同结果。

阅读英文原文

实现说明

UnsignedPacking和函数 main提供全部行为。

使用要点

  • 演示输出是带标签的(toUnsignedString =、signed view =、divideUnsigned =),每个操作都会留下自己的一行标注。

常见问题

运行「Integer 无符号口径解析与运算」会打印什么?

整个文件跑完,输出行以 toUnsignedString =、signed view =、divideUnsigned = 这类前缀开头。

核心语句

int packed = Integer.parseUnsignedInt("4294967295");
int high = Integer.parseUnsignedInt("2147483648");

代码示例

public class UnsignedPacking {

    public static void main(String[] args) {
        // 2^32-1 超出 int 正数范围,但可以按 unsigned 语义解析进 int
        int packed = Integer.parseUnsignedInt("4294967295");
        System.out.println("toUnsignedString = " + Integer.toUnsignedString(packed));
        System.out.println("signed view      = " + packed);

        // 无符号除法按 4294967295 计算;普通 / 按负数 -1 计算,结果不同
        System.out.println("divideUnsigned    = " + Integer.divideUnsigned(packed, 2));
        System.out.println("plain divide      = " + (packed / 2));
        System.out.println("remainderUnsigned = " + Integer.remainderUnsigned(packed, 10));
        System.out.println("plain remainder   = " + (packed % 10));

        // 比较同理:0x80000000 无符号下大于 5,有符号下是 Integer.MIN_VALUE
        int high = Integer.parseUnsignedInt("2147483648");
        System.out.println("compareUnsigned(0x80000000, 5) = " + Integer.compareUnsigned(high, 5));
        System.out.println("compare(0x80000000, 5)         = " + Integer.compare(high, 5));
    }
}