Search code examples
chexsubtraction

Subtracting Hexadecimals


When I declare a variable as float and subtract two hexadecimal numbers, I keep getting different answer everytime I compile and and run it. Where as the if I declare an integer variable the result stays the same everytime I compile and run the code. I don't understand why storing the result in float changes everytime I compile with the difference of the same two numbers (0xFF0000 - 0xFF7FF)

int main()
{
   float BlocksLeft = 0xFF0000 - 0xFF7FF;
   int BLeft = 0xFF0000 - 0xFF7FF;

   printf("%08x\n", BlocksLeft);
   printf("%08x\n", BLeft);
}

Solution

  • The following line is incorrect:

    printf("%08x\n", BlocksLeft);
    

    %x format will indicate compiler the argument you give is an int. This lead to undefined behavior. I tried to compile your code and I got:

    >gcc -Wall -Wextra -Werror -std=gnu99 -o stackoverflow.exe stackoverflow.c
    stackoverflow.c: In function 'main':
    stackoverflow.c:15:4: error: format '%x' expects argument of type 'unsigned int', but argument 2 has type 'double' [-Werror=format=]
        printf("%08x\n", BlocksLeft);
        ^
    

    Please, try to compile with stronger warning level, at least -Wall.

    You can correct your program this way, for instance:

    #include <stdio.h>
    
    int main()
    {
        float BlocksLeft = 0xFF0000 - 0xFF7FF;
        int BLeft = 0xFF0000 - 0xFF7FF;
    
        printf("%08x\n", (int) BlocksLeft); // Works because BlocksLeft's value is non negative
        // or
        printf("%08x\n", (unsigned int) BlocksLeft);
        // or
        printf("%.8e\n", BlocksLeft);
    
        printf("%08x\n", BLeft);
    }