Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

./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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading