How to use ~ (tilde) operator in C

1 Answer

0 votes
#include <stdio.h>

/*
The ~ (tilde) operator performs a bitwise NOT operation - 
all the 1 bits are set to 0 and all the 0 bits are set to 1
creates the complement of a number
*/

void print_bits(int n, int size) {
    for (int i = 1 << (size - 1); i > 0; i = i / 2) {
        (n & i) ? printf("1") : printf("0");
    }
}

int main() {
    int n = 43241;
    print_bits(n , 16);
    
    printf("\n");
    
    n = ~n;
    print_bits(n , 16);

    return 0;
}



/*
run:

1010100011101001
0101011100010110

*/

 



answered Jun 7, 2024 by avibootz

Related questions

1 answer 240 views
2 answers 172 views
172 views asked Nov 1, 2021 by avibootz
2 answers 151 views
151 views asked Nov 1, 2021 by avibootz
2 answers 142 views
142 views asked Nov 1, 2021 by avibootz
...