Search code examples
cintsigned

3 byte signed value to 4byte signed value


I have a 3 byte signed value:

0xffe8a4

That I need to store in a 4 byte signed (32bit) INT, as the sign bit is located at bit 24 doing a straight cast to a 32bit INT does not preserve the negative element of the value and so changes it to a positive number.

How do I do the conversion to a 32bit number and preserve the original intended value?

Thanks in advance!


Solution

  • You could test the sign bit, and if it's 0, prepend you number with 0x00, otherwise prepend it with 0xff. Like so (warning: didn't test it):

    int yourCustomNumberIsStoredHere = 0xffe8a4; //I know it won't actually be your number, because int is 4 byte, but I don't know how your store it in your program.
    int result = yourCustomNumberIsStoredHere;
    if (yourCustomNumberIsStoredHere & (0x80 << 16))
        result |= 0xff << (24);
    

    A reference on the topic: Wikipedia: Two's complement (how negative numbers are stored in memory).