Bit Operations in C

The following program explains four basic bit operations.

  • Set a Bit
  • Clear a Bit
  • Toggle a Bit
  • Test a Bit
  • Print the integer in bit format
More Functions GitHub : 


<#Read Me:
    Developed By:
                Name:Vaneeswaran N
                www.vaneeswaran.com
#>
/* The following program is the sample for bit operation

//Header File Declaration
#include<stdio.h>
#include<string.h>

//Macro Definition

#define SET_BIT(ipb,n) (ipb|= 1 << n) //ipb is the input byte and n is the position 
#define CLR_BIT(ipb,n) (ipb &= ~(1<<n))
#define TOG_BIT(ipb,n) (ipb^= 1 << n)
#define TEST_BIT(ipb,n) (ipb&=(1<<n))

void print_byte(unsigned int input)
{
int i;
printf("\nBinary Form:");
for (i = 0; i < 32; i++) 
 printf("%d",(((input << i) & 0x80)>0)?1:0);
printf("\n");
}

int main(void)
{
unsigned int input=0; // we are dealing with bit operation so unsigned int should be used to work with 32 bit.
int bit_pos=0;
printf("\nEnter the Number and Position :");
scanf("%d%d",&input,&bit_pos);
bit_pos-=1;//To make bit position more convenient for user 


//To Set a bit:

printf("\nByte Before Set:%d",input);
print_byte(input);
unsigned int output=SET_BIT(input,bit_pos);
printf("\nByte After Set:%d",output);
print_byte(output);

//End of Set Bit


//To Clear a bit:

printf("\nByte Before Clear:%d",input);
print_byte(input);
unsigned int output=CLR_BIT(input,bit_pos);
printf("\nByte After Clear:%d",output);
print_byte(output);

//End of clear Bit

//To Toggle a bit:

printf("\nByte Before Toggle:%d",input);
print_byte(input);
unsigned int output=TOG_BIT(input,bit_pos);
printf("\nByte After Toggle:%d",output);
print_byte(output);

//End of Toggle Bit

//To Test a bit:
int flag=TEST_BIT(input,bit_pos);
printf("\nBit Test Value:%d",flag);
}
//End of Test Bit