5

I am trying to perform a bitwise or on a byte value I have in Java.

For example, I am running:

byte b = (byte)0b11111111;
int result = 0 | b;

My expected result for this would be 0b00000000 00000000 00000000 11111111, or 255. However, I am receiving -1, or 0b11111111 11111111 11111111 11111111.

I'm assuming that Java converts my byte into an int via sign extension before performing the operation, and I was just curious if there was a way to get my desired result without using a bit mask (0b11111111).

1
  • 1
    "without using a bit mask" The answer is to use a bitmask. There isn't really a way around that in Java. Commented Jan 28, 2015 at 22:16

1 Answer 1

7

Using a bit mask is the standard solution to disable sign extension when converting a byte to an int. You'll just have to accept this slice of Java ugliness.

int result = 0 | (b & 0xFF);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.