22 / 123
Which bitwise operator is suitable for checking whether a particular bit is ON or OFF?
to check if the ith bit is on or off in a number n following bitwise operation is used.
flag = n&(1<<i) ;
if the value of flag is zero then the bit is set otherwise not.
explanation of above approach is as follows.
1. lets assume n is 9 so its bitwise operator is 1001 and bitwise representation of 1 is 0001
2.to check if 4th bit is on we do left shift by 4 on 1 (1<<4) which shift the bits in one to left by 4 unit now the (1<<4)=1000
3.Finally bitwise and operation is performed so 1001&1000 = 1000 which is not zero so it means that 4th bit of 9 is set
Asked In ::
Lakshmi
23 Feb, 2019 5:07 AM
to check if the ith bit is on or off in a number n following bitwise operation is used.
flag = n&(1<<i) ;
if the value of flag is zero then the bit is set otherwise not.
explanation of above approach is as follows.
1. lets assume n is 9 so its bitwise operator is 1001 and bitwise representation of 1 is 0001
2.to check if 4th bit is on we do left shift by 4 on 1 (1<<4) which shift the bits in one to left by 4 unit now the (1<<4)=1000
3.Finally bitwise and operation is performed so 1001&1000 = 1000 which is not zero so it means that 4th bit of 9 is set
to check if the ith bit is on or off in a number n following bitwise operation is used.
flag = n&(1<<i) ;
if the value of flag is zero then the bit is set otherwise not.
explanation of above approach is as follows.
1. lets assume n is 9 so its bitwise operator is 1001 and bitwise representation of 1 is 0001
2.to check if 4th bit is on we do left shift by 4 on 1 (1<<4) which shift the bits in one to left by 4 unit now the (1<<4)=1000
3.Finally bitwise and operation is performed so 1001&1000 = 1000 which is not zero so it means that 4th bit of 9 is set
Bitwise AND