1

I want to convert the int to byte and put into the byte array like the following code:

    private int StartByte       = 0xF1;
    private int GetProductInfo  = 0xA0;
    private int NoDataByte      = 0xFF;
    private int EndByte         = 0xED;

byte[] params = new byte[]{(byte)(StartByte & 0xFF),
                           (byte)(GetProductInfo & 0xFF),
                           (byte)(NoDataByte & 0xFF),
                           (byte)(EndByte & 0xFF)};

And I show the content like the following code:

for(int i=0 ; i <params.length ; i++){
  Log.d(TAG,"params["+i+"] = " + params[i]);
}

The log show like the following:

params[0] = -15
params[1] = -96
params[2] = -1
params[3] = -19

But the 0xF1 should be 241 not -15 , and the 0xA0 should be 60 not -96 I already do & 0xFF.

Did I missing something ?

Thanks in advance.

Wun
  • 6,211
  • 11
  • 56
  • 101
  • Yes you should display the values in the array also hexadecimal. Then you will see that they are still the same. – greenapps May 03 '17 at 08:44
  • And `byte` is not signed or unsigned. Its just eight bits. You can interpret them as you like. – greenapps May 03 '17 at 08:48
  • `I already do & 0xFF.`. On the wrong place. You should do that while displaying the byte values of the array. – greenapps May 03 '17 at 08:55

1 Answers1

0

Try using long instead of int.

EDIT *There are no Uints in Java as discussed here: * Declaring an unsigned int in Java

You will have to use signed values.

Community
  • 1
  • 1
Ben Brookes
  • 419
  • 4
  • 15