Unsigned Integer Parse Divide Compare

Parse, divide, and compare ints in the unsigned domain so values beyond Integer.MAX_VALUE keep their meaning across parseUnsignedInt and compareUnsigned.

JavaData Integrity

Code

snippet
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));
    }
}

The same bit pattern, two interpretations

Integer.parseUnsignedInt("4294967295") accepts a value beyond Integer.MAX_VALUE and stores it as the bit pattern 0xFFFFFFFF — which the signed view prints as -1. The file then runs paired operations on that one int: unsigned division by 2 computes over 4294967295 and yields 2147483647, while the plain / operator sees -1 / 2 and yields 0. The remainder pair differs the same way (5 unsigned, -1 signed).

The paired operator results

toUnsignedString = 4294967295
signed view      = -1
divideUnsigned    = 2147483647
plain divide      = 0
remainderUnsigned = 5
plain remainder   = -1
compareUnsigned(0x80000000, 5) = 1
compare(0x80000000, 5)         = -1

The last pair uses high = Integer.parseUnsignedInt("2147483648") — the bit pattern 0x80000000. Unsigned, it is larger than 5 (compareUnsigned returns 1); signed, it is Integer.MIN_VALUE, so compare returns -1.

The line that flips the interpretation

System.out.println("divideUnsigned    = " + Integer.divideUnsigned(packed, 2));

Nothing about the stored bits changes — the unsigned methods reinterpret them per operation, which is the entire contract of the …Unsigned family.

Interactive Tools for This Topic

FAQ

What does Unsigned Integer Parse Divide Compare print when run?
Invoke the file as-is — the `toUnsignedString =`, `signed view =`, `divideUnsigned =` prefixes identify which step printed each line.