0

I want to send an integer coded as a byte array over a serial line with C and receive it using java and put the array back to an java int.

I'm using rs-232 to send four bytes in a byte array packed by a C union. (The slightly odd typedef is caused by the Arduino C dialect) Here I send for example the decimal value 600 It is packed in a type accordingly:

typedef union {
  uint16_t integer;
  byte binary[4];
} binaryInteger;

and sent using the function:

void mcProxySend(binaryInteger bi){
  for (byte i = 0; i < 4 ; i ++) {
    mcProxySend(bi.binary[i]);
  } 
}

mcProxySend is just a serial write with occasional escape characters.

I have the receiving end of my Java classes worked out. Data is flowing and, bit by bit, it is the same as I sent.

The problem I have is how to reassemble the broken up integer.

Einar Sundgren
  • 4,325
  • 9
  • 40
  • 59

3 Answers3

0

Since I found out the answer at the same time as I wrote this question I will post my solution.

The value of dec 6000 is bin 1011101110000 and by the union it is split in

b[0] = 0 //(MSB) 
b[1] = 0
b[2] = 10111
b[3] = 1110000 //(LSB)

Similar to the answer is in this thread the solution is to bitshift the binary values to the new integer. This will recreate the byte structure of the original one, assuming they are of the same bit length.

Community
  • 1
  • 1
Einar Sundgren
  • 4,325
  • 9
  • 40
  • 59
0

You should use an identical union on the receiver side (taking possible byte-order swaps into account) then write the receive bytes into the b field and once you have all four just extract the resulting value from the integer field.

Oh, the receiver is Java - never mind!

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • The answer would be that simple if the receiver was C, wouldn't it. If the concept of unions are added to Java recently as in Java 8, please let me know, I might have missed it. – Einar Sundgren Aug 07 '14 at 13:54
  • Yes, it would be that simple, which is why I left the answer there for posterity (as "community wiki") rather than just deleting it. – Alnitak Aug 07 '14 at 13:55
0

Assuming big-endian byte order, Java has a function in java.io.Bits.getInt(byteArray, offset). Sadly it is not declared public. But its implementation can easily be used to learn from.

Here is its implementation, it simply promotes each byte to an int, slides it along to the correct place and bit-ands the values together.

static int getInt(byte[] b, int off) {
    return ((b[off + 3] & 0xFF)      ) +
           ((b[off + 2] & 0xFF) <<  8) +
           ((b[off + 1] & 0xFF) << 16) +
           ((b[off    ]       ) << 24);
}
Chris K
  • 11,622
  • 1
  • 36
  • 49