1

When I XOR a byte lets say -1(in byte) with 2(int) I get -3 as a result whereas I want the operation to give me a positive int. This is due to the 2's complement representation and type promotion. I want to know if there a way I can use unsigned byte in java.

int x = 2;
byte y = -1;
System.out.println(x^y);

Output

-3

I found two excellent similar questions here and here. But I want some method or bitwise operation to return an int which can be later converted into byte without 2's complement representation.

Community
  • 1
  • 1
  • The sign-extension of `y` doesn't really matter by itself, the low 8 bits of the result are still what you want, so if you're going to convert back to byte anyway it will be correct. – harold Feb 02 '17 at 15:09

2 Answers2

0

All types except char (and boolean) are signed.

To get an unsigned-equivalent value, you can use a wider type and use a mask:

public static int unsigned(byte value) {
    return value & 0xff;
}

public static int unsigned(short value) {
    return value & 0xffff;
}

public static long unsigned(int value) {
    return value & 0xffffffffl;
}

Since Java 8, the standard API provides methods for that (e.g. Byte.toUnsignedInt(…)).

rom1v
  • 2,752
  • 3
  • 21
  • 47
0

The only unsigned type in Java is a char, which is a 16 bit unsigned integer.

You could make use of that.

Mask away the more significant bytes using & 0xff if you need to.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483