5

I have a array of bytes.

bytes[] = [43, 0, 0, -13, 114, -75, -2, 2, 20, 0, 0]

I want to convert it to unsigned bytes in Java. this is what I did: created a new array and copy the values with & 0xFF:

    this.bytes = new byte[bytes.length];
    for (int i=0;i<bytes.length;i++)
        this.bytes[i] = (byte) (bytes[i] & 0xFF);

but the values stay negative in the new array as well. what am I doing wrong?

Ohad
  • 1,563
  • 2
  • 20
  • 44
  • 7
    There is no unsigned bytes in Java. – Sweeper Oct 26 '17 at 08:53
  • What do you expect an operation like ``byteValue & 0xFF`` to do? – f1sh Oct 26 '17 at 08:56
  • 3
    @f1sh It does the right thing in terms of converting a signed byte into an unsiged `int`. If you just cast a byte with a negative value e.g. into an `int` you end up with an `int` with that negative number. So that part of the code wasn't the problem, just the one where it's put back (i.e. casted again) into a `byte` ending up with the same negative value you started with. – Lothar Oct 26 '17 at 09:09

2 Answers2

13

bytes in Java are always signed.

If you want to obtained the unsigned value of these bytes, you can store them in an int array:

byte[] signed = {43, 0, 0, -13, 114, -75, -2, 2, 20, 0, 0};
int[] unsigned = new int[signed.length];
for (int i = 0; i < signed.length; i++) {
    unsigned[i] = signed[i] & 0xFF;
}

You'll get the following values:

[43, 0, 0, 243, 114, 181, 254, 2, 20, 0, 0]
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Java has no thing called an unsigned byte. You have to use other types like short or int to be able to hold values > 127.

Lothar
  • 5,323
  • 1
  • 11
  • 27