How to flip (invert) all the bits in a variable, turning a 1 into a 0 and a 0 into a 1 in C

1 Answer

0 votes
#include <stdio.h>

char *toBinFormat(int n);

int main(int argc, char **argv) 
{ 
    // flip/invert (~)
    // result bits invert. turning a 1 into a 0 and a 0 into a 1
    
    char tmp;
    
    tmp = 7; 
    printf("%3d = %s\n", tmp, toBinFormat(tmp));
    
    tmp = ~tmp;
    printf("%3d = %s\n", tmp, toBinFormat(tmp));
    
    return(0);
}

char *toBinFormat(int n)
{
    static char binary_value[9]; // without static binary_value is a local 
                                 // array that disappear after return
    int i;
    
    for(i = 0; i < 8; i++)
    {
        binary_value[i] = n & 0x80 ? '1' : '0';
        n <<= 1;
    }
    binary_value[i] = '\0';

    return binary_value;
}

/*
run:

  7 = 00000111
 -8 = 11111000

*/

 



answered Jun 14, 2015 by avibootz

Related questions

1 answer 147 views
147 views asked Apr 1, 2019 by avibootz
1 answer 248 views
1 answer 76 views
1 answer 120 views
120 views asked Feb 27, 2023 by avibootz
1 answer 112 views
1 answer 183 views
1 answer 307 views
...