...

/

Solution Review: Turn On the 3rd and 5th Bits

Solution Review: Turn On the 3rd and 5th Bits

Follow the step-by-step instructions to turn on the 3rd and 5th bits.

We'll cover the following...

Solution

RUN the code given below and see its output!

Press + to interact
# include <stdio.h>
# define _BV(x) ( 1 << x )
void showbits ( unsigned char n ) ;
short unsigned int onBits (short unsigned int num) ;
int main( )
{
unsigned char b;
short unsigned int num ;
num = 211;
onBits (num);
}
// Shows the bits in a number
void showbits ( unsigned char n )
{
int i ;
unsigned char j, k, andmask ;
for ( i = 7 ; i >= 0 ; i-- )
{
j = i ;
andmask = 1 << j ;
k = n & andmask ;
k == 0 ? printf ( "0" ) : printf ( "1" ) ;
}
}
short unsigned int onBits (short unsigned int num)
{
unsigned char a, mask ;
num = num & 0x00FF ;
a = num ;
showbits (a);
printf("\n");
// Turns on 3rd bit if it is off
mask = _BV( 3 ) ;
if ( ( a & mask ) != mask )
a = a | mask ;
// Turns on 5th bit if it is off
mask = _BV( 5 ) ;
if ( ( a & mask ) != mask )
a = a | mask ;
showbits (a);
printf("\n");
return a;
}

Explanation

To turn on the bit, first, we have to select the appropriate mask value based on the value that should be turned on.

Lines 36-38: If you want to turn on ...

Access this course and 1400+ top-rated courses and projects.