Recombining 2 bytes into a signed int

Sending a byte stream over from an Arduino which includes some int16_t values (little endian) but struggling to recombine them. This is as close as I can get, but I loose the sign.

          int1 = (inBuffer[1]<<8) | inBuffer[0]&0xff;
          int2 = (inBuffer[3]<<8) | inBuffer[2]&0xff;
          int3 = (inBuffer[5]<<8) | inBuffer[4]&0xff;
          int4 = (inBuffer[7]<<8) | inBuffer[6]&0xff;

Thanks.

forum.Processing.org/two/discussion/17900/out-of-control-y-axis-rolling-graph#Item_1

Thanks but I can’t see an answer to my question there.

I need to use a byte stream for speed.

Sending ASCII and dealing with strings and tokens is way too slow for my requirements.

Java’s corresponding datatype is short.

I’ve got this example sketch which uses a FloatBuffer:
forum.Processing.org/two/discussion/12757/transmission-of-a-float-through-a-serial-link#Item_5

But you can easily adapt it to use a ShortBuffer instead:
docs.Oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#asShortBuffer–

However I think you’re gonna need to switch your Arduino code to send bytes as big endian, which is the default protocol for transmission AFAIK.

Hello,

Did you try:

int1 = ( (0xff & inBuffer[1]) << 8) |  ( (0xff & inBuffer[0]) << 8)

I think that should work.

It does not work.

Correction:

:)

1 Like

oops, thanks for the correction =)

1 Like