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.






Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.