How to use bitwise NOT "!" in C

1 Answer

0 votes
#include <stdio.h>

char *toBinFormat(int n);

int main(int argc, char **argv) 
{ 
    // NOT (!)
    // result changes any 1 value to 0, and the value 0 to 1 
    // affects all the bits, not reverses
    
    char tmp;
    
    tmp = 7; 
    printf("%3d = %s\n", tmp, toBinFormat(tmp));
    
    tmp = !tmp;
    printf("%3d = %s\n", tmp, toBinFormat(tmp));
    
    tmp = 0;
    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
  0 = 00000000
  0 = 00000000
  1 = 00000001

*/

 



answered Jun 14, 2015 by avibootz
edited Jun 14, 2015 by avibootz

Related questions

1 answer 246 views
1 answer 252 views
2 answers 356 views
1 answer 297 views
1 answer 177 views
...