C Chapter 12 Bitwise
C Chapter 12 Bitwise
2
Review – Bitwise Operations in Integers
Corresponding bits of both operands are combined by the
usual logic operations.
5
Other Bitwise Operators
• Examples:
unsigned short int i, j, k;
i = 21; /* i is now 21 (binary 0000000000010101) */
j = 56; /* j is now 56 (binary 0000000000111000) */
k = ~i; /* k is now 65514 (binary 1111111111101010) */
k = i & j; /* k is now 16 (binary 0000000000010000) */
k = i ^ j; /* k is now 45 (binary 0000000000101101) */
k = i | j; /* k is now 61 (binary 0000000000111101) */
Bitwise XOR
printf("Output = %d", a|b); 00010101 = 21 (In decimal)
Complement=11
printf("complement=%d\n",~35);
printf("complement=%d\n",~-12);
lights: 00000100
10
Setting Bits
For instance, how can we turn off
the light in room #3?
lights: 00100111
lights: 00100011
11
Getting Bits
How can we know if a bit is on
or off?
Manipulations
on bits are
enabled by mask and bitwise
operators.
Bitwise AND of anything with 1
results in the same value.
12
Getting Bits
For instance, how can we check if
the light in room #3 is turned on or
off?
lights: 00100111
char lights = 0x27;
char mask = 0x1;
mask <<= 2; mask: 00000001
if(lights & mask)
mask: 00000100
puts(“turned on”);
else
puts(“turned off”); lights & mask: 00000100
13
Questions-1
m=0x0080;
for(k=8;k>0;k--)
{ X=36
if(x&m)
{ printf("1"); } X=24 (0x24=16*2+1*4) and X=36
else
{ printf("0"); }
00100100
m=m>>1;
}
while(binnum!=0)
{
rem=binnum%10;
decnum=decnum+rem*i;
i=i*2;
binnum=binnum/10;
}
}
Alternative Way For Question-2
int main(int argc, char *argv[]) {
long binnum,sum=0,i=0;
printf("Enter A binary Number=");
scanf("%ld",&binnum);
while(binnum!=0)
{
if(binnum%10==1) {sum=sum+pow(2,i);}
binnum=binnum/10;
i++;
}
printf("The Decimal form =%d",sum);
return 0;
}
Bit Fields & Bitwise 18
Operations
Question-3
• What is the output of the given program in C
int main(int argc, char *argv[]) {
int num, count, ms, i, bit;
bit=8; num=6; count = 0;
ms = 1 << (bit - 1);
for(i=0; i<bit; i++)
{
if((num << i) & ms) break;
count++;
}
printf("Total number in %d is %d", num, count);
return 0;
} Bit Fields & Bitwise 19
Operations
Example for Final Exam
Write a C program to convert decimal to binary number and count
trailing zeros in a binary number for 8 bits.
• Ask to the user to enter any number in decimal form.
• You must NOT use any bitwise operators for converting and
displaying the binary form.
• You must use bitwise the operators for finding trailing zeros in
binary number.
• You must use only for loop.
• Display the result on the screen like this:
20
Answer for Final Exam
int main(int argc, char *argv[]) {
int arr[50]={0},arrbin[50]={0};
int num,numbin, count=0, i;
printf("Enter any number: "); scanf("%d", &num);
numbin=num;
for(i=7;i>=0;i--)
{ 0 1 2 3 4 5 6 7
arr[i]=numbin%2; 0 0 0 1 1 1 1 0
numbin=numbin/2;
}