×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

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 and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.