Search code examples
c++hexunsigned-integer

how to get a signed int from an unsigned hex in C++?


I have been trying and searching for hours now but I just don't get how I can get an negative integer from an unsigned hex. I get 24 bit hex numbers and want signed integers.

(to clarify: I get an get a 24 bit number in hexadecimal. Then I read it as an integer and then I want to give it out as a signed integer.)

0xfffef1 for example should be -271 but I don't know how to get there.

Looking forward for some advice.

I have tried to invert the 24bit and then add one like you do with binary but I don't really know how to do that either.


Solution

  • Completing the 2 complement with the most significant byte should work fine:

    #include <iostream>
    
    int main () {
    
        int a = 0xfffef1;
        a |= 0xff << 24;
        std::cout << a << std::endl;
    }
    

    See the Live Demo.