# Converting 2s complement 24-bit and 32-bit into signed integer

I have an external ADC that delivers three bytes of 2s complement data for a 24-bit signed integer result. I'm having problems with Sketch properly converting the numbers:

``````union sfp24bit {
byte b[2];
signed long int result;
} tval;
byte incomingdata[2];

......

// convert three bytes of 2s complement into 24 bit signed integer
tval.b[2] = incomingdata[2]; // high byte
tval.b[1] = incomingdata[1]; // middle byte
tval.b[0] = incomingdata[0]; // low byte
tval.result /= 2;
``````

Any ideas on getting the conversion to operate properly in Sketch?

``````union sfp24bit {
byte b[4];
long result;
} tval;

byte incomingdata[3];

// convert three bytes signed 24 bit integer to signed long
tval.b[0] = incomingdata[0]; // low byte
tval.b[1] = incomingdata[1]; // middle byte
tval.b[2] = incomingdata[2]; // high byte
tval.b[3] = (incomingdata[2] & 0x80 ? 0xFF : 0);
``````

Thank you for the response.

does the result still need to be calculated?

``````tval.result /= 2;
``````

Also, I see Sketch needs variables b[0] ... b[3] to be declared as b[4].

Array indexes start at zero, so a 4 element array is indexed 0 to 3.

``````byte incomingdata[3];
long val = 0;

......

// convert three bytes of 2s complement into 24 bit signed integer
if (incomingdata[2] & 0x80)
val = 0xff;
val = (val << 8) | incomingdata[2];
val = (val << 8) | incomingdata[1];
val = (val << 8) | incomingdata[0];
// val is now a 32-bit signed integer
``````

Regards,
Ray L.

RayLivingston, the 24-bit solution works perfectly. Thank you for the elegant solution.

I've been tinkering with getting it to work with 4 bytes of incoming data (32-bit). Can you adjust your solution for 4 bytes of incoming data?