1

I'm struggling a bit with binary in Java and Python to translate a program

In python when I execute the following commands, I've got

>>> print ord(pack('>H', 32809)[0])
128

>>> print ord(pack('>H', 32809)[1])
41

In Java, I expect to have the same result when I execute the following command, but it's not there:

bsh % print ((byte)((32809 & 0xFF00) >> 8)); 
-128

bsh % print ((byte)(32809 & 0x00FF)); 
41

Can somebody explain me why 128 is negative in Java? Many thanks.

0

3 Answers 3

2

Byte in java is a signed data type - and yeah I never understood why they did that either. You'll need to use a short (well since all bit ops are used on ints anyhow, just use a int really) and ignore the higher 8bit (otherwise sign extension would be a problem)

 System.out.println(((short) ((32809 & 0xFF00) >> 8)) & 0xFF);
Sign up to request clarification or add additional context in comments.

1 Comment

Or just System.out.println((32809 >> 8) & 0xFF);
1

A signed byte has a range of -128..127, so (127+1) == -128

2 Comments

does it means (byte)128 = -128 ?
Yes. Incrementing from 127 "wraps around" - the bit pattern for 127 is 0x7F; adding one gives 0x80; interpreted as a signed byte, this is -128. There are not enough bits in a signed byte to properly represent +128.
0

You won't have unsigned types in Java. You could consider casting it to a short or an int instead.

2 Comments

BTW char is an unsigned type. ;)
That's true, it is. But as far as numbers are concerned, you won't have unsigned types. Yes, I know it is valid to say char c = 100; but seeing how java.lang.Character doesn't extend Number, I don't consider it to be a number.

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.