Search⌘ K

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

Understand how to turn on specific bits in an integer using bitwise operators in C. This lesson guides you through selecting the correct mask and using the OR operator to modify the 3rd and 5th bits without affecting others.

We'll cover the following...

Solution

RUN the code given below and see its output!

C
# 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 the 3rd3^{rd} bit, then the 3rd3^{rd} ...