Signed And Unsigned Right Shift Differ

Arithmetic right shift copies the sign bit so -8 stays negative, while unsigned shift fills zeros and turns the same bits into a huge positive.

JavaData Integrity

Code

snippet
public class ShiftSigns {

    public static void main(String[] args) {
        int negative = -8; // 0xFFFFFFF8

        // >> 算术右移:符号位复制进高位,负数保持负数
        System.out.println("-8 >> 1  = " + (negative >> 1));  // -4
        System.out.println("-8 >> 28 = " + (negative >> 28)); // -1

        // >>> 逻辑右移:高位补 0,同一串位变成巨大的正数
        System.out.println("-8 >>> 1  = " + (negative >>> 1));  // 2147483644
        System.out.println("-8 >>> 28 = " + (negative >>> 28)); // 15

        // 正数两者结果相同:符号位本来就是 0
        System.out.println("8 >> 1 = " + (8 >> 1) + ", 8 >>> 1 = " + (8 >>> 1));

        // 经典用途:无符号中点防溢出 —— lo+hi 溢出成负数后,>>> 仍能还原正确中点
        int lo = 1_500_000_000, hi = 1_800_000_000;
        int mid = (lo + hi) >>> 1;
        System.out.println("mid = " + mid); // 1650000000
    }
}

Signed And Unsigned Right Shift Differ, line by line

Structurally, expect the class ShiftSigns and the function main and nothing else.

Points of care

  • The language toolchain is the sole prerequisite.

Applying it

Entry signature: public static void main(String[] args)

The -8 >> 1 =, -8 >> 28 =, -8 >>> 1 = prefixes mark which step produced each printed line.

Statements that matter

int lo = 1_500_000_000, hi = 1_800_000_000;
int mid = (lo + hi) >>> 1;

Interactive Tools for This Topic

FAQ

What does Signed And Unsigned Right Shift Differ print when run?
Run it as a complete program — the output lines carry labels such as `-8 >> 1 =`, `-8 >> 28 =`, `-8 >>> 1 =`.