C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

Bitwise One's Compliment (Bitwise NOT Operator) in C language

Bitwise Ones Compliment also known as Bitwise NOT Operator (~) is a unary operator in C language which operates on single operator only, it flips (toggles) the all bits of a number from 0 to 1 and 1 to 0.

Consider this example

#include <stdio.h>
//function to print binary
void getBinary(int n)
{
    int loop;
    /*loop=7 , for 8 bits value, 7th bit to 0th bit*/
    for(loop=7; loop>=0; loop--)
    {
        if( (1 << loop) & n)
            printf("1");
        else
            printf("0");
    }
}

int main()
{
	unsigned char var=0x0A;

	printf("Before flipping bits, var: %02X\n",var);
	printf("Binary is: ");
	getBinary(var);
	
	printf("\n\n");
	
	//flipping the bits
	var= ~var;
	
	printf("After flipping bits, var: %02X\n",var);
	printf("Binary is: ");
	getBinary(var);
	printf("\n");	
	
	return 0;
}





Output

Before flipping bits, var: 0A 
Binary is: 00001010 

After flipping bits, var: F5
Binary is: 11110101

See, the output before flipping the bits value of var is 0x0A (Binary: 00001010) and after flipping the bits through Bitwise One's Compliment (~) the value of var is 0xF5 (Binary: 11110101).

You can see, all bits are changed from 0 to 1 and 1 to 0.


COMMENTS