6

I need to represent a value of 0xFF00 as two bytes (in Java). I am trying to do it like this:

int val = 0xFF00; bytearray[0] = (byte)((val >> 8) & 0xFF); bytearray[1] = (byte)((val >> 0) & 0xFF); 

I know that byte in Java can hold values 0-255. So I expect the first array element to have a value of 255 and the second element to be zero. But what I am getting instead is -1 and 0. What I am doing wrong? What this -1 value mean?

1 Answer 1

10

Byte in java is from -128 to 127, not from 0 to 255

-1 is 1111 1111 in two's complement binary, equal to 255 in unsigned byte.

You aren't doing anything wrong, you just need to know that if you see -1, it means the byte is representing the bits 1111 1111.

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

2 Comments

@ Esailija: Thank you! You see my problem is that a specific protocol (Modbus) requires me to include this value of FF 00 to my byte request but it doesn't accept -1 value that results from my shifting operations :) Is there any way for me to represent this value as an unsigned byte? Thanks!
@IgorAtman the problem has to be elsewhere, if you write raw byte with value of -1 into a file, that file will then contain 0xFF

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.