Search code examples
cfloating-pointbitwise-operators

How to flip the sign of a float using bitwise operators in C


This is the code I have so far

// given the 32 bits of a float return it with its sign flipped
uint32_t sign_flip(uint32_t f) {
    int mask = 1;    
    f = ~f; // 1's Complement 
    while (mask > 0 && (mask & f)) 
    { 
        f ^= mask; 
        mask <<= 1; 
    } 
    f ^= mask; // 2's complment 
    return f; // REPLACE ME WITH YOUR CODE
}

Expected output:

./sign_flip -42
sign_flip(-42) returned 42

output:

./sign_flip -42
sign_flip(-42) returned 0.10546875

How would I go about fixing this? I am not sure what the issue is


Solution

  • IEEE 754 floating-point format is not 2's complement. Just flip most-significant bit:

    float f = 42;
    *(uint32_t*)&f ^= (1 << 31);
    printf("%f\n", f);