1
Hex:[0A][52][08][01][01][01][00][CD][21][02][59]


0      [0A]
1      [52]         Packettype    = TEMP_HUM
2      [08]         subtype       = TH8 - 
3      [01]         Sequence nbr  = 1
4/5    [01][01]     ID            = 257
6/7    [00][CD]     Temperature   = 20.5 °C
8      [21]         Humidity      = 33
9      [02]         Status        = Dry
10     [5] *nibble           Signal level  = 5
11     [9] *nibble           Battery       = OK

So I get 11 bytes (Hex) in over the serial port. I assigned all the bytes to a byte array so that I can use them later.

I have two qestions:

1] How can I combine the 4 & 5 bytes back together in Java (I am presuming in an INT) ? 2] How can you extract 10 and 11 or the High and Low nibbles of the last byte ?

[FROM COMMENTS BELOW] Example Byte: High[0101][0110]Low lowNibble = yourbyte & 0x0f; 01010110 & 0x0f (00001111) = 00000110

           highNibble = yourByte >>>> 4
           01010110 >>> 4 = 00000101


          IF you use this Example Byte: High[1101][0110]Low
          highNibble = yourByte >>> 4
          11010110 >>> 4 = 00000101
          Because >>> removes the signed bit.
DevilCode
  • 1,054
  • 3
  • 35
  • 61

1 Answers1

6

1) It depends on the endianness. It will either be (b[4] << 8) | b[5] or (b[5] << 8) | b[4]

2) lowNibble = yourByte & 0x0f; highNibble = (yourByte >> 4) & 0x0f;

You can also do: lowNibble = yourByte & 0x0f; highNibble = yourByte >>> 4;

The unsigned shift (>>>) fills the upper bits with zero, regardless of the sign.

Eduardo
  • 8,362
  • 6
  • 38
  • 72
  • Byte = 11111111 by doing &0x0F you get 00001111 Byte = 11111111 by doing >> 4 you get 11110000 then what does the 0x0f do ? Sorry for being dull just not getting it clearly yet. – DevilCode Feb 02 '13 at 20:44
  • By doing 11111111 >> 4 you get 10001111 because of the sign. Anding with 0x0f gets rid of the one caused by the sign. Note that 01111111 >> 4 = 00000111 because the sign bit was not set. – Eduardo Feb 02 '13 at 20:56
  • Byte: High[0101][0110]Low lowNibble = yourbyte & 0x0f; 01010110 & 0x0f (00001111) = 00000110 highNibble = yourByte >>>> 4 01010110 >>> 4 = 00000101 IF Byte: High[1101][0110]Low highNibble = yourByte >>> 4 11010110 >>> 4 = 00000101 Because >>> removes the signed bit. – DevilCode Feb 02 '13 at 21:20
  • I don't understand the question in your last comment – Eduardo Feb 02 '13 at 21:22
  • it was just an example to check i got it correct i will put in the question as the formatting is brutal in the comments – DevilCode Feb 02 '13 at 21:23
  • I didn't know if it was a question or a statement :-) But I think you got it right. Of course, the final answer is in testing it – Eduardo Feb 02 '13 at 21:23
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23846/discussion-between-devilcode-and-eduardo) – DevilCode Feb 02 '13 at 21:29