Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

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 134 views
134 views asked Apr 1, 2019 by avibootz
1 answer 234 views
1 answer 59 views
1 answer 105 views
105 views asked Feb 27, 2023 by avibootz
1 answer 107 views
1 answer 168 views
1 answer 289 views
...