We have used this function quite often in this chapter. Now we have sufficient knowledge of bitwise operators and hence are in a position to understand it. The function is given below followed by a brief explanation.
showbits ( int n )
{
int i, k, andmask ;
for ( i = 15 ; i >= 0 ; i-- )
{
andmask = 1 << i ;
k = n & andmask ;
k == 0 ? printf ( "0" ) : printf ( "1" ) ;
}
}
All that is being done in this function is using an AND operator and a variable andmask we are checking the status of individual bits. If the bit is OFF we print a 0 otherwise we print a 1.
First time through the loop, the variable andmask will contain the value 1000000000000000, which is obtained by left-shifting 1,
showbits ( int n )
{
int i, k, andmask ;
for ( i = 15 ; i >= 0 ; i-- )
{
andmask = 1 << i ;
k = n & andmask ;
k == 0 ? printf ( "0" ) : printf ( "1" ) ;
}
}
All that is being done in this function is using an AND operator and a variable andmask we are checking the status of individual bits. If the bit is OFF we print a 0 otherwise we print a 1.
First time through the loop, the variable andmask will contain the value 1000000000000000, which is obtained by left-shifting 1,
fifteen places. If the variable n’s most significant bit is 0, then k would contain a value 0, otherwise it would contain a non-zero value. If k contains 0 then printf( ) will print out 0 otherwise it will print out 1.
On the second go-around of the loop, the value of i is decremented and hence the value of andmask changes, which will now be 0100000000000000. This checks whether the next most significant bit is 1 or 0, and prints it out accordingly. The same operation is repeated for all bits in the number.
On the second go-around of the loop, the value of i is decremented and hence the value of andmask changes, which will now be 0100000000000000. This checks whether the next most significant bit is 1 or 0, and prints it out accordingly. The same operation is repeated for all bits in the number.
No comments:
Post a Comment