Professional Documents
Culture Documents
0 U1 Bitwise Operators
0 U1 Bitwise Operators
x=21=0001 0101
y=37=0010 0101
Bitwise AND &
x & y = 00000101=5
Bitwise OR I
x | y = 00111010=53
Bitwise Exclusive OR ^
x ^ y =00110000=48
Bitwise shift operators
– Right shift >>
– Left shift <<
x=21=0001 0101
y=37=0010 0101
• ~ is a unary operator.
• inverts all the bits represented by its operand.
• often combines with the bitwise operator to
turn off a particular bit.
• a=01 then ~a=10
• flag= a& ~a; =00
• eg:~x= 11101010=2’s complement(00010101)
• =-22
Bitwise operators
#include<stdio.h>
#include<conio.h> o/p
void main()
{ c=0 d=30
int a=10,b=20,c,d,e,f,g,h;
clrscr();
1.a=a^b=111=7
2.b=a^b=011=3
3.a=a^b=100=4
a=4,b=3
Method 2
• a=3 =011
• b=4=100
1.a=a+b=3+4=7
2.b=a-b=7-4=3
3.a=a-b=7-3=4
a=4,b=3
Masking
• Shift operators, when combined with the logical
operators, are useful for extracting data from an
integer field that holds multiple pieces of information.
This process is called as masking.
• It refers to the process of extracting desired bits
from(or transforming desired bits in) a variable by
using logical bitwise operation.
• The operand(a constant or variable) that is used to
perform masking is called the mask.
• Eg:
y=x & mask;
y=x | mask;
Masking …
• Masking is used in different ways:
• To decide bit pattern of an integer variable.
• To copy a bit pattern to a new variable, while
remainder of the new variable is filled with 0s.
(using bitwise AND)
• To copy a bit pattern to a new variable, while
remainder of the new variable is filled with 1s.
(using bitwise OR)
• To copy a bit pattern to a new variable, while
remainder of the original bit pattern is inverted
within the new variable.(using bitwise Exclusive OR)
/*convert decimal to binary */
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
void convert(int);
clrscr();
printf("Enter a decimal number:");
scanf("%d",&num);
printf("\nThe equivalent binary number of %d is: ",num);
convert(num);
getch();
}
/*function to convert decimal to binary*/
void convert(int num)
{
int i,bit,ANDmask;
for(i=15;i>=0;i--)
{
ANDmask=1<<i;
bit=num & ANDmask;
if(bit==0)
printf("0");
else
printf("1");
}
printf("\n");
}
/************output**************
Enter a decimal number:12