C Programming - Bitwise Operators - Discussion
Discussion Forum : Bitwise Operators - Point Out Correct Statements (Q.No. 4)
4.
Which of the following statements are correct about the program?
#include<stdio.h>
int main()
{
unsigned int m[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
unsigned char n, i;
scanf("%d", &n);
for(i=0; i<=7; i++)
{
if(n & m[i])
printf("yes");
}
return 0;
}
Discussion:
13 comments Page 2 of 2.
Abhishek said:
8 years ago
Suppose n=2.
Binary representation as, 0000 0000 0000 0010.
Now when, i=0, m[0]=0x01(in hexa) hence in binary 0000 0000 0000 0001.
n & m gives 0 (as & gives 1 only when 1 is present in same position in both numbers).
i becomes 1, m[1]=0x02 hence in binary, 0000 0000 0000 0010
n&m gives 1 hence yes is printed.
i becomes 2, m[2]=0x04 hence in binary, 0000 0000 0000 0100
n&m gives 0 again.
Just like this, it will keep checking.
Remember when m=0x10 then in binary, 0000 0000 0001 0000.
and m=0x20 then in binary, 0000 0000 0010 0000.
As you can see m value converted to binary keeps shifting the value of 1 one position to the left till m=0x80 that is, 0000 0000 1000 0000.
Hope it helps.
Binary representation as, 0000 0000 0000 0010.
Now when, i=0, m[0]=0x01(in hexa) hence in binary 0000 0000 0000 0001.
n & m gives 0 (as & gives 1 only when 1 is present in same position in both numbers).
i becomes 1, m[1]=0x02 hence in binary, 0000 0000 0000 0010
n&m gives 1 hence yes is printed.
i becomes 2, m[2]=0x04 hence in binary, 0000 0000 0000 0100
n&m gives 0 again.
Just like this, it will keep checking.
Remember when m=0x10 then in binary, 0000 0000 0001 0000.
and m=0x20 then in binary, 0000 0000 0010 0000.
As you can see m value converted to binary keeps shifting the value of 1 one position to the left till m=0x80 that is, 0000 0000 1000 0000.
Hope it helps.
(1)
Rahul said:
8 years ago
It is clear now. Thanks @Abhishek.
Quein said:
7 years ago
Please explain it clearly.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers