Reputation: 101
Ok this is probably something really stupid, but I can't understand why this isn't working;
byte temp = (byte)0x80;
System.out.println(temp);
byte holder = (byte)(temp | 0x40);
System.out.println(holder);
Produces:
-128
-64
Shouldn't a bitwise or on:
10000000
01000000
Yield
11000000
or -192?
Upvotes: 3
Views: 86
Reputation: 21004
0x80
represent 128 and 0x40
represent 64. If you print 0x80 | 64
it will output 192.
When you cast to byte 128
becomes -128
as 128 is higher then Byte.MAX_VALUE
which is 127.
So the expression you evaluate is -128 | 64
, while you were probably expecting 128 | 64
, and will result in your output, -64
.
Upvotes: 3
Reputation: 51
Try printing them out this way instead:
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);
Upvotes: 0