# 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;
signed long int result;
} tval;
byte incomingdata;

......

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

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

``````union sfp24bit {
byte b;
long result;
} tval;

byte incomingdata;

// convert three bytes signed 24 bit integer to signed long
tval.b = incomingdata; // low byte
tval.b = incomingdata; // middle byte
tval.b = incomingdata; // high byte
tval.b = (incomingdata & 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 ... b to be declared as b.

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

``````byte incomingdata;
long val = 0;

......

// convert three bytes of 2s complement into 24 bit signed integer
if (incomingdata & 0x80)
val = 0xff;
val = (val << 8) | incomingdata;
val = (val << 8) | incomingdata;
val = (val << 8) | incomingdata;
// 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?