m7hacke
m7hacke

Reputation: 31

How do I convert a Hex value (example: 0xD1) to a unsigned Byte in Java?

I am trying to take hex values and move them into a byte array. When I do this they are not converted how I need them to be. Most of them are converted to negative numbers. For example, after the execution of the C# code "baCommandPDI[0] = 0xD1;", the value of baCommandPDI[0] is "209". This is what I need. No matter what I try in Java, the value is "-47". I need it to be "209" in the byte array, because this byte array is sent out over TCP/IP to some external hardware. The external hardware cannot interpret -47 as 209. It must be 209. I have tried the following code:

int intTemp = 0xD1; After this line is executed the value of intTemp is 209, great!

int intHexValue = 0xD1 & 0xFF; After this line is executed the value of intHexValue is still 209, I don't understand how, but it ia what it is.

baCommand[0] = (byte) intHexValue; After this line is executed the value of baCommand[0] is -47, bad. This is not what I want. Everytime it converts the value to a byte it makes it signed.

Is there any other way I can do this? Can I use 11010001 and some how assign that value to a byte without making it negative?

Upvotes: 1

Views: 1899

Answers (2)

rgettman
rgettman

Reputation: 178253

In Java, bytes are always signed. But like an unsigned byte in another language, 8 bits are still used. The byte representations for 209 (unsigned) and -47 are the same.

1101 0001

The only difference is how Java interprets the most significant bit -- -128 vs. 128 in an unsigned type. The difference is 256, which is the difference between 209 and -47. You can send the value as is, because the bit values are the same, only the interpretations of this bit pattern are different.

If you would like to convert the value -47 to 209 to convince yourself in Java, you can promote the type to a longer primitive type and mask out the last 8 bits. This line will do this is one line, so you can debug and see that the bits are the same and that the unsigned version is equivalent.

int test = baCommandPDI[0] & 0xFF;

Printing/debugging test will let you see the value 209.

Upvotes: 3

jmoo
jmoo

Reputation: 71

Java does not have a concept of unsigned bytes.

To get 209 from 0xD1, try:

0xD1 & 0xFF;

Upvotes: 0

Related Questions