C Program to find the ith Bit of a Binary Number - Bit Manipulation


 
// Program by Akash Tripathi (@proakash256) 
 
// Example : Let n = 100110101 and i = 5
// So Bit at 5th position is 1

// In this Program position starts from 1
// but in binary representation it starts from 0

// Two Methods are discussed below :

#include <stdio.h>
void binary(int n)
{
    // Prints the Binary Representation
    // of a Decimal Number upto 11 bits.
    for(int i = 10i >= 0i = i - 1)
    {
        printf("%d" , ((n >> i) & 1));
    }
    printf("\n");
    return;
}
int method1(int , int);
int method2(int , int);
int main()
{
    int n , i;
    printf("Enter the Number : ");
    scanf("%d", &n);
    printf("Binary Representation of %d is : "n);
    binary(n);
    printf("Enter the Position : ");
    scanf("%d", &i);
    printf("\nBy First Method :\n");
    printf("Bit at Position %d is %d\n\n",
            i , method1(n , i));
    printf("By Second Method :\n");
    printf("Bit at Position %d is %d\n\n",
            i , method1(n , i));
    return 0;
}
int method1(int n , int i)
{
    // In this method we right shift(>>)
    // the binary number i times and then
    // AND(&) it with 1

    // if ((n >> i) & 1) == 1 then the bit is 1
    // if ((n >> i) & 1) == 0 then the bit is 0
    i = i - 1;
    int mask = n >> i;
    
    if((mask & 1) == 1)
        return 1;

    else if((mask & 1) == 0)
        return 0;
}
int method2(int n , int i)
{
    // In this method we left shift(<<)
    // 1 i times and then AND(&) it with
    // the binary number

    // if ((1 << i) & n) == (Non Zero No.)
// then the bit is 1
 
    // if ((1 << i) & n) == 0 then the bit is 0
    i = i - 1;
    int mask = 1 << 1;

    if((mask & n) == 0)
        return 0;
        
    else
        return 1;
}

Comments