To get a particular bit from a number

This program is to get a particular bit from a number

To solve this problem we will be taking two approach:

First Approach:
Right shift the number by that bit, and(&) that 1. If the result is 1 means that bit is 1 else 0

#include <stdio.h>

int find_bit (int num, int pos)
{
  return ((num >> pos) & 1);
}

int main()
{
  int num, pos;
  printf("\n Enter the number: ");
  scanf("%d", &num);
  printf("\n Enter the position: ");
  scanf("%d", &pos);
  
  int res = find_bit(num, pos -1);
  if(res)
     printf("\n The given bit is 1\n");
  else
     printf("\n The given bit is 0 \n");
  return 0;
}

Output:

 Enter the number: 8
 Enter the position: 4

 The given bit is 1

Second Approach:
In this we do not right shift the number rather we get the another number such that all the bit if that number is 0 except the bit given. And then we and(&) the original number with the second number. If the result is 1, the given bit is 1 else 0.

#include <stdio.h>

int find_bit (int num, int pos)
{
  /* This gives us the number where all bit is unset except at position "pos" */
  int mask = 1UL << pos;
  return (mask & num);
}

int main()
{
  int num, pos;
  printf("\n Enter the number: ");
  scanf("%d", &num);
  printf("\n Enter the position: ");
  scanf("%d", &pos);
  
  int res = find_bit(num, pos);
  if(res)
     printf("\n The given bit is 1\n");
  else
     printf("\n The given bit is 0 \n");
  return 0;
}

Output:

 Enter the number: 7
 Enter the position: 3

 The given bit is 1


Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: