0

This may seem like an easy question, but I'm so confused.

byte[] bArray = new byte[]{(byte) (0x80 & 0xff)};
System.out.println(bArray[0]);

and my output is -128. Why? How can I rewrite this so that the byte array contains 128? I thought that the 0xff made it unsigned. Thanks for your help!

1
  • 1
    You put the result into a byte. All Java bytes are signed. You could convert it to an int after reading it from the byte array. Commented Jun 29, 2017 at 19:37

4 Answers 4

9

I thought that the 0xff made it unsigned.

Well, it does, sort of - it promotes it to an int, and keeps just the last 8 bits.

However, you're then casting the result of that back to a byte, and a byte in Java is always signed. (It's annoying, but it's the way it is.) So you might as well just have written:

byte[] bArray = { (byte) 0x80 };

The result would be exactly the same.

You're storing the bit pattern you want to store (10000000) so if you're transmitting this elsewhere, you don't need to worry... it's just when you're viewing it as a byte in Java that it's annoying.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way to write it so that the byte array contains 128 and not -128?
@namsayin: No, because 128 is out of the range of a byte, because bytes are signed... You will never get a byte in Java that's not in the range -128 to 127 inclusive.
@namsayin bytevalue 0 is basically 128 if it was unsigned
@namsayin: there is no such byte as 128 and no way to store it in any kind of holder of bytes.
|
3

My answer is attached in the big picture enter image description here

1 Comment

as you can see the max. value is 127, so if you want 128 you need to upgrade to short type instead of byte type.
3

Value range of byte according Java Language Specification 4.2.1

For byte, from -128 to 127, inclusive

so there is no way (in Java) that a byte will hold (byte) 128.

You can cast¹ the byte to an int and apply & 0xff to get the unsigned representation of the byte (as an int). But if you cast it back to an byte it will again be interpreted as being a signed value between -128 and 127...

If only concerned with printing, you can do:

System.out.println(bArray[0] & 0xff);

or, for hexadecimal

System.out.printf("0x%02x\n", bArray[0]);

1 - the & operator will automatically convert the byte to an int

Comments

0

You can copy values to integer and switch negative values into its positive 'unsigned' value:

byte[] bytes = [-1, 10, -128];
    
int[] ints = new int[bytes.length];
for (int idx = 0 ; idx < bytes.length ; idx++) {
    byte b = bytes[idx];
    ints[idx] = b < 0 ? 256 + b : b;
}

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.