Search code examples
c++binarybytesigned

Get signed integer from 2 16-bit signed bytes?


So this sensor I have returns a signed value between -500-500 by returning two (high and low) signed bytes. How can I use these to figure out what the actual value is? I know I need to do 2's complement, but I'm not sure how. This is what I have now -

real_velocity = temp.values[0];
    if(temp.values[1] != -1)
        real_velocity += temp.values[1];

    //if high byte > 1, negative number - take 2's compliment
    if(temp.values[1] > 1) {
        real_velocity = ~real_velocity;
        real_velocity += 1;
    }

But it just returns the negative value of what would be a positive. So for instance, -200 returns bytes 255 (high) and 56(low). Added these are 311. But when I run the above code it tells me -311. Thank you for any help.


Solution

  •  -200 in hex is 0xFF38, 
    

    you're getting two bytes 0xFF and 0x38, converting these back to decimal you might recognise them

    0xFF = 255,
    0x38 = 56
    

    your sensor is not returning 2 signed bytes but a simply the high and low byte of a signed 16 bit number.

    so your result is

    value = (highbyte << 8) + lowbyte
    

    value being a 16 bit signed variable.