Why is this bitwise operation not working?

Ok, this is probably something really stupid, but I can't figure out why it doesn't work.

    byte temp = (byte)0x80;
    System.out.println(temp);
    byte holder = (byte)(temp | 0x40);
    System.out.println(holder);

      

Outputs:

-128

-64

Should not be bitwise or on:

10,000,000

01000000

Output

11000000

or -192?

+3


source to share


2 answers


0x80

represent 128 and 0x40

represent 64. If you print 0x80 | 64

, it outputs 192.

When you transfer a byte 128

it becomes -128

like 128 Byte.MAX_VALUE

, which is 127.



Thus, the expression that you estimate -128 | 64

, while you probably expect 128 | 64

, and you get the result -64

.

+3


source


Try to print them this way:



byte b1 = (byte)0x80; String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0'); System.out.println(s1); byte b2 = (byte)0x40; String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0'); System.out.println(s2); byte b3 = (byte)(b1 | b2); String s3 = String.format("%8s", Integer.toBinaryString(b3 & 0xFF)).replace(' ', '0'); System.out.println(s3);

0


source







All Articles