Java bitwise byte operation

public static void main(String[] args) throws Exception {
    for (int i = 0, k = 20; i < Integer.MAX_VALUE; i++) {
        final Byte b = (byte) -1; // new Byte((byte) -1) works fine
        final int x = b.byteValue() & 0xff;
        if (x == -1) System.out.println(x + " is -1 (" + i + ")");
        if (x != 255) {
            System.out.println(x + " is not 255 (" + i + ")");
            if (x == -1) System.out.println(x + " is not 255 but -1 (" + i + ")");
            if (--k == 0) break;
        }
        if (i % 100 == 0) Thread.sleep(1); // or other operations to make this code run slower
    }
}

Execution Output:

-1 is not 255 (110675)
-1 is not 255 but -1 (110675)
/ is not 255 (168018)
/ is not 255 (168019)
/ is not 255 (168020)
/ is not 255 (168021)
/ is not 255 (168022)
/ is not 255 (168023)
/ is not 255 (168024)
/ is not 255 (168025)
/ is not 255 (168026)
/ is not 255 (168027)
/ is not 255 (168028)
/ is not 255 (168029)
/ is not 255 (168030)
/ is not 255 (168031)
/ is not 255 (168032)
/ is not 255 (168033)
/ is not 255 (168034)
/ is not 255 (168035)
/ is not 255 (168036)

who can explain the result of the conclusion. the test should be run in jdk1.8.0_20 or jdk1.8.0_25 or jdk1.8.0_31 and with the option "-server". I think this is a mistake, and I sent a bug report to oracle, but have not received a response yet.

+4
source share
1 answer

I think I found a problem that causes this behavior; it was placed in OpenJDK as error 8042786 and, indeed, is related to autoboxing. Running Java with -XX:-EliminateAutoBoxseems to be a valid workaround and fixes this problem.

. , , -, SO.

VM , , , , :

110674 C1, , C2 main , C2 :

  • b.byteValue() & 0xff , x 0 255. , x == -1 .
  • java.lang.System - , System.out.println , , .
  • b.byteValue() & 0xff, , , , and, , x, ( movsbl). , x 32 , , x 0-255.

, , x == -1 , C2 , x != 255 , , , x 255 ( , Byte.valueOf() b.byteValue() , , -, , ). , System.out, , . x "" -1 .

C1- , C2 java.lang.System. :

  • , x == -1 .
  • java.lang.System , x + " is not 255 (" + i + ")" . Integer.toString(), , ( , x ), , , x , 1 ( 10). , '0' + -1; , /.

, .:)

+3

All Articles