Error while executing OR bit-bit and 32-bit bit extension in Java

I am having trouble understanding bit mut OR in java. I am reading a Java programming book called "Apress Beginning Java7" by Jeff Friesen.

And in this book on page 31, the author gave two 8-bit binary numbers and performed a bit-wise OR on these two numbers. He said that:

0B0001 1010 | 0B1011 0111 results 0000 0000 0000 0000 0000 0000 1011 1111

Then he said this, and I quote:

"The operators &, ^, and | in the last three lines will first convert their byte integer operands to 32-bit integer values ​​(by expanding the signed bit, copying the value of the signed bits to extra bits) before performing their operations."

Now, if I understand correctly, the first 8-bit number ( 0B0001 1010 ) becomes the extension of the sign bit (32-bit number):

0B0000 0000 0000 0000 0000 0000 0001 1010

And the second number ( 0B1011 0111 ) with the extension of the sign bit becomes:

0B1111 1111 1111 1111 1111 1111 1011 0111

If I am bitwise OR these two extended numbers, I get:

0B1111 1111 1111 1111 1111 1111 1011 1111

But the author received:

0B0000 0000 0000 0000 0000 0000 1011 1111

Can anyone tell me where I am going wrong? I mean, can someone kindly tell me why my answer is different from the author and where I made a mistake?

+4
source share
1 answer

0B10110111 binary literal is of type int . This is implicitly promoted from byte , so there is no sign extension.

If it was (byte)0B10110111 , then you will have what you expect.

+1
source

All Articles