Array of Bytes (as hex) conversion to Int issue. (Kotlin/Java)

Mannie :

I'm looking at parsing information from a temp/humidity sensor that was provided with the following instructions;

There are 6 bytes.

  1. Temperature positive/negative: 0 means positive (+) and 1 means negative (-)

  2. Integer part of temperature. Show in Hexadecimal.

  3. Decimal part of temperature. Show in Hexadecimal.

  4. Reserved byte. Ignore it.

  5. Integer part of humidity. Show in Hexadecimal.

  6. Decimal part of humidity. Show in Hexadecimal.

For example: 00 14 05 22 32 08 means +20.5C 50.8% & 01 08 09 00 14 05 means -8.9C 20.5%

as each byte is in hex & i need to covert this to an Int I followed this approach - Java code To convert byte to Hexadecimal but the values I get when validating their example don't make sense.In Kotlin I do;

val example = byteArrayOf(0, 14, 5, 22, 32, 8)
example.map { Integer.parseInt(String.format("%02X ", it),16)}

First Example output is;

0 = "00 "
1 = "08 "
2 = "09 "
3 = "00 "
4 = "0E "
5 = "05 "

Second Example output;

0 = "00 "
1 = "0E "
2 = "05 "
3 = "16 "
4 = "20 "
5 = "08 "

What am I doing wrong? I'm starting to think the manufactures instructions could be 'misleading'

Matt :

A key thing you are missing here is that when passing in the it parameter to String#format, that value is a decimal int, not a hexadecimal int.

You instead want to map the value in the array directly to a string, then get its decimal value:

byte it = 14;
int x = Integer.parseInt(String.valueOf(it), 16);
System.out.println(x); // This will print 20

This should get you the expected result.


Note, your problem is slightly confusing because the numbers in your byte array are decimal numbers...already in their hex 'format'. There are a few ways this confusion can be fixed (assuming you have control of the array's type and/or contents):

  • Use String instead of byte
String it = "14";
int x = Integer.parseInt(it, 16);
System.out.println(x); // This will print 20
  • Store the values as hex and still convert (i.e., putting a 0x in front of each number)
byte it = 0x14;
int x = Integer.parseInt(String.format("%02X", it), 16);
System.out.println(x); // This will print 20
  • Store the values as hex and don't convert, because there is no need
byte it = 0x14;
System.out.println(it); // This will print 20

If you go with the second bullet, though convoluted, what you have right now should work, but the third option would be best if you are hardcoding in the byte array's values.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131826&siteId=1