Showing posts with label XOR. Show all posts
Showing posts with label XOR. Show all posts

C program for Bitwise Operation.

To know more about Bitwise operation please read the Bitwise Operator in C. It explains how these bitwise operator work in C

#include <stdio.h>
void main(void)
{
    int i=165,j=281;
    printf("Bitwise AND operation of %d and %d is %d \n", i,j, i&j);
    printf("Bitwise OR operation of %d and %d is %d \n", i,j, i|j);
    printf("Bitwise XOR operation of %d and %d is %d \n", i,j, i^j);
    printf("2 bits right shift of %d is %d \n", i, i>>2 );
    printf("3 bits left shift of %d is %d \n", i, i<<3);
    printf("NOT operation of %d is %d \n", i, ~i);

}


Bitwise Operator in C

In the C programming language, operations can be performed on a bit level using bitwise operators.

Following are the six bitwise operators provided by C for bit manipulation
Symbol Operator
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ bitwise NOT (one's complement) (unary)

To understand these operation lets ahead with two example..
We know that in C, integer consumed 2 bytes or 16 bit memory. So the binary representation of 165 and 281 as the following

(165)10 = (10100101)2

(281)10 = (100011001)2

But in C when it consumed 16 bits, it will like the following..

165 = 0000000010100101

281 = 0000000100011001

These extra bits(0's) are added to make it 16 bit integer number. Now the operation take place as..

Now remains the shift operations, yeah..
You will clear by seeing the following two images of Right shift (>>) and Left Shift (<<)

Right Shift >>

To understand the operation we shifted it by 2 bits. All the bits of the number (165) shifted to right by 2 bits.

Left Shift

To understand it we shifted the number by 3 bits, all the bits of the number (165) shifted to left by 3 bits

NOT operation

We first complement each bit of the number (i.e., replace '1' by '0' and '0' by '1') To know more about 1's and 2's Complement

bitwise not operator
See the C program With All the bitwise operation