简体   繁体   中英

Java “int i = byte1 | 0x0200” vs “int i = byte1”?

In the page Wikipedia - Shifts in Java :

In bit and shift operations, the type byte is implicitly converted to int . If the byte value is negative , the highest bit is one, then ones are used to fill up the extra bytes in the int. So

 byte b1=-5; int i = b1 | 0x0200; 

will give i == -5 as result.

I understand that 0x0200 is equal to 0b0000 0010 0000 0000 . But what is the significance of 0x0200 in the passage shown above?

I mean— b1 | 0x0200 b1 | 0x0200 will always be equal to i (see " My Test " below), then in the passage above, why not simply write byte b1=-5; int i = b1 byte b1=-5; int i = b1 ?

My Test :

public static void main(final String args[]) {
    final byte min_byte = Byte.MIN_VALUE; // -128
    final byte limit = 0; // according to the bolded words in the passage
    for (byte b = min_byte; b < limit; ++b) {
        final int i1 = b;
        final int i2 = b | 0x0200;
        if (i1 != i2) { // this never happens!
            System.out.println(b);
        }
    }
}

But what is the significance of 0x0200 in the passage shown above?

This is done for illustration purposes only: the value 0x200 ORs in a one in a position that is equal to 1 already. The idea is to show that the result is not 0x000002FB , but actually -5 , ie 0xFFFFFFFB .

I understand that 0x0200 is equal to 0b1111 1110 0000 0000

No, it isn't. The correct value is given by,

int i = 0x0200; // <-- decimal 512
System.out.println(Integer.toBinaryString(i));

Which outputs

1000000000

If we examine your second value,

byte b1 = -5;
System.out.println(Integer.toBinaryString(b1));

We get

11111111111111111111111111111011

Lining up both numbers

11111111111111111111111111111011
00000000000000000000001000000000

It seems clear that the result will be the bit value of -5 (since the only 0 in -5 is also 0 in 0x0200 ). To determine the significance we can examine

int i = 0x0200; // <-- Decimal 512
System.out.println("Dec: " + Integer.toBinaryString(i).length());

Output

Dec: 10

So, the given bitwise OR will force the tenth bit to be true. It was true in your input byte, but if you used - Decimal 1535 ( 0b 101 1111 1111 ) then you would get,

System.out.println(1535 | 0x0200);

Output is

2047

Because if you perform a bitwise-or on the two numbers

01000000000
10111111111

you get

11111111111

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM