Interview questions on bitwise operators in C

Interview questions on bitwise operators in c

You are looking for Bitwise Operators in C interview questions or tricky Bitwise Operators in C interview questions, then you are at the right place. In my previous post, I have created a collection of “c interview questions”  and “embedded c interview questions that are liked by many people. I have got the response to create a list of interview questions on “bitwise operators in C”. So here I have tried to create a collection of Interview questions on bitwise operators in C. I have spent many hours creating these C bitwise operators interview questions. So I hope you will enjoy these tricky bitwise operators’ questions in C and you will learn new things about bitwise operators.

 

Q) Compute the sign of an integer?

The MSB bit of a number defines their sign. If the MSB bit is set, the number will be negative.

#include <stdio.h>

int main()
{
    int sign = 0;
    int data = 0;

    printf("Enter the number\n");

    scanf("%d",&data); //Get the number

    sign = (data > 0) - (data < 0); // check the sign of the number

    if(sign == 1)
    {
        printf("Enter number is a positve number\n");
    }
    else if(sign == -1)
    {
        printf("Enter number is a negative number\n");
    }
    else
    {
        printf("Enter number is zero\n");
    }

    return 0;
}

 

Q) Detect if two integers have opposite signs?

The two integers have different signs if their MSB (bit) is different. Using the EX-OR operator, we can check the sign of the integers.

We know that for the same input EX-OR produces the low output and for the different input it produces the high output.

E.g.

              BIT1                BIT2  BIT1  ^  BIT2
                1                   1                       0
                0                   0                       0
                1                   0                       1
                0                   1                       1

Let the given integers are “a” and “b”. The EX-OR of sign bit (MSB) of “a” and “b” will be 1 if the MSB of “a” and “b” is different. In other words, we can say, EX-OR of “a” and “b” will be negative if “a” and “b” have the opposite signs.

#include<stdbool.h>
#include<stdio.h>

bool CheckOppositeSign(int a, int b)
{
    bool bRetValue = 0;

    bRetValue = ((a ^ b) < 0); // 1 if a and b have opposite signs

    return bRetValue;
}

int main()
{
    int a = 0,b=0;
    bool bRetValue;

    //ENTER THE VALUE OF a & b
    printf("Enter the Value of a = ");
    scanf("%d",&a);

    printf("\nEnter the Value of b = ");
    scanf("%d",&b);

    bRetValue = CheckOppositeSign(a, b); // check signs of a & b

    if (true == bRetValue)
    {
        printf ("\nIntegers have the opposite sign\n\n");
    }
    else
    {
        printf ("\nInteger have the same sign\n\n");
    }

    return 0;
}

 

 

Q) Write a program to check an integer is a power of 2?

Here, I am writing a small algorithm to check the power of 2. If a number is a power of 2, the flag will be 1.

#include <stdio.h>

int main()
{
    int flag = 0;
    int data = 0;

    printf("Enter the number ");
    scanf("%d",&data); //Get the number

    flag = ((data != 0) && !(data & (data - 1))); // check the power of 2
    if(flag == 1)
    {
        printf("Number is a power of 2 \n");
    }
    else
    {
        printf("Enter number is not power of 2 \n");
    }

    return 0;
}

 

 

Note: Here I assume that bit of register starts with 0th position, it means the 2nd position is actually 3rd bits.

D7 D6 D5 D4 D3 D2 D1 D0

Q) How to set a particular bit in C?

Setting a Bits

Bitwise OR operator (|) use to set a bit of integral data type.”OR” of two bits is always one if any one of them is one.

An algorithm to set the bits

Number  | =  (1<< nth Position)

A simple program to set a bit:

 

#include <stdio.h>


int main(int argc, char *argv[])
{

    unsigned char cData=0x00;
    int iPos =0;

    printf("cData = 0x%x\n\n",cData);

    printf("Enter the position which you want set = ");
    scanf("%d",&iPos);

    //Set the nth bit.
    cData|=1<<iPos;

    //Print the data
    printf("\n\n%dth Bit Set Now cData will be = 0x%x\n",iPos,cData);


    return 0;
}

 

 

Q) How to clear a particular bit in C?

Bitwise AND operator (&) use to clear a bit of integral data type. “AND” of two bits is always zero if any one of them is zero.

An algorithm to clear the bits

Number  &=  ~ (1<< nth Position)
To clear the nth bit, first, you need to invert the string of bits then AND it with the number.

A simple program to clear a bit:

 

#include <stdio.h>

int main(int argc, char *argv[])
{
    unsigned char cData=0xFF;
    int iPos =0;

    printf("Initially cData = 0x%x\n\n",cData);

    printf("Enter the position which you want clear = ");
    scanf("%d",&iPos);

    //clear the nth bit.
    cData &= ~(1<<iPos);

    //Print the data
    printf("\n\n%dth Bit clear Now cData will be = 0x%x\n",iPos,cData);

    return 0;
}

 

Q) How to check if a particular bit is set in C?

To check the nth bit, shift the ‘1’ nth position toward the left and then “AND” it with the number.

An algorithm to check the bits

 Bit = Number & (1 << nth)

 

A simple program to check a bit:

 

#include <stdio.h>

int main(int argc, char *argv[])
{
    unsigned char cData=0xFc;
    int iPos =0;

    printf("Initially cData = 0x%x\n\n",cData);

    printf("Enter the position which you want check = ");
    scanf("%d",&iPos);

    if(cData & (1<<iPos))   //Check bit set or not
    {
        printf("\n\nBit is One\n");
    }
    else
    {
        printf("\n\nBit is zero\n");
    }

    return 0;
}

 

 

Q) How to toggle a particular bit in C?

Bitwise XOR (^) operator use to toggle the bit of an integral data type. To toggle the nth bit shift the ‘1’ nth position toward the left and “XOR” it.

An algorithm to toggle the bits

Number  ^=  (1<< nth Position)

 

A simple program to toggle a bit:

 

#include <stdio.h>

int main(int argc, char *argv[])
{

    unsigned char cData=0xF8;
    int iPos =0;

    printf("Initially cData = 0x%x\n\n",cData);
    printf("Enter the position which you want toggle = ");
    scanf("%d",&iPos);

    //toggle the nth bit.
    cData ^= 1<<iPos;

    //Print the data
    printf("\n\n%dth Bit Set Now cData will be = 0x%x\n",iPos,cData);

    return 0;
}

 

 

Q) Write an Efficient C Program to Reverse Bits of a Number?

There are a lot of ways to reverse the bits of a number, here I am describing three general methods to reverse the bits.

Method 1:

In this method, we will check the set bits of num and run the loop through all the bits of an integer. If we find the ith bits of num is set then just put 1 at the ((INT_BITS – 1) – ith ) position of tmp, where INT_BITS is the number of bits of an integer.

#define CHAR_BITS  8  // size of character
#define INT_BITS  ( sizeof(int) * CHAR_BITS)


//bit reversal function
unsigned int ReverseTheBits(unsigned int num)
{
    unsigned int iLoop = 0;
    unsigned int tmp = 0;         //  Assign num to the tmp
    int iNumberLopp = INT_BITS;

    for(; iLoop < iNumberLopp; ++iLoop)
    {

        if((num & (1 << iLoop))) // check set bits of num
        {
            tmp |= 1 << ((INT_BITS - 1) - iLoop); //putting the set bits of num in tmp
        }
    }

    return tmp;
}

 

 

Method 2:

It is a simple algorithm to reverse bits of the 32-bit integer. This algorithm uses the eight constant value for reversing the bits and takes five simple steps.

In the below section, I am describing the functioning of each step.

Steps 1:
num = (((num & 0xaaaaaaaa) >> 1) | ((num & 0x55555555) << 1));

This expression used to swap the bits.
Let an example, suppose num is 0100, after the above expression it will be 1000.

Steps 2:
num = (((num & 0xcccccccc) >> 2) | ((num & 0x33333333) << 2));

Above expression uses to swap the 2 bits of a nibble. Suppose num is 10 00, after the above expression, it will be 00 01.

Steps 3:
num = (((num & 0xf0f0f0f0) >> 4) | ((num & 0x0f0f0f0f) << 4));

An expression used to swaps the nibbles. like if num is 0011 0010 then after the above expression it will be 0010 0011.

Steps 4:
num = (((num & 0xff00ff00) >> 8) | ((num & 0x00ff00ff) << 8));

This statement uses to swap the bytes of an integer. Let num is 00001000 00001100, after the above expression, it will be 00001100 00001000.

Steps 5:
((num >> 16) | (num << 16));

The above expression uses to swap the half-word of an integer. Means that if the num is 0000000011001110 1000100100000110 after the above result number will be 1000100100000110 0000000011001110.

//bit reversal function
unsigned int ReverseTheBits(register unsigned int x)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));

    return((x >> 16) | (x << 16));
}

 

Q) Write a program to count set bits in an integer?

There are a lot of ways to count the number of bits in a given integer, here I am writing two approaches naive and  Brian Kernighan’s.

In naive approach requires one iteration per bit until no more bits are set.

#include <stdio.h>

#define CHAR_BITS  8  // size of character
#define INT_BITS  ( sizeof(int) * CHAR_BITS)


int main()
{
    unsigned int CountSetBits = 0; //Total number of bit set.

    unsigned int n = 0; //Variable that set bits you want to count

    printf("Enter the Number ");
    scanf("%d", &n);
    while (n)
    {
        CountSetBits += n & 1;
        n >>= 1;
    }
    printf("Number of 1 = %d", CountSetBits);
}

 

Brian Kernighan’s method goes through as many iterations as there are set bits.

1. Initialize CountSetBits = 0

2. If integer n is not zero.

( a ). Perform bitwise operation and assign the value back to the n.
These bitwise operations clear the least significant.
n &= (n – 1);

( b ). Increment CountSetBits by 1.

( c ). Again go to step 2.

3. If there are no set bits remaining then return CountSetBits.

#include <stdio.h>

#define CHAR_BITS  8  // size of character
#define INT_BITS  ( sizeof(int) * CHAR_BITS)


int main()
{
    unsigned int n = 0; //Variable that set bits you want to count
    unsigned int CountSetBits = 0; //Total number of bit set

    printf("Enter the Number ");
    scanf("%d", &n);
    while(n)
    {
        n &= (n - 1); // clear the least significant bit set
        CountSetBits++;
    }

    printf("Number of 1 = %d", CountSetBits);
}

 

 

Q) Rotate bits of a number in C?

Like the assembly in C language, there is no operator to rotate the bits, so if we require rotating a bit, then we have to do it manually.

Basically, bit rotation is similar to the shift operation except that in shift operation the bits that fall off at one end are put back to the other end.

There are two types of rotation possible left and right. In the left rotation, the bits that fall off at the left end are put back at the right end and in the right rotation, the bits that fall off at the right end are put back at the left end.

Example:
If data is stored using 8 bits, then the left rotation of a data 32(‭‬00100000‬) by 2 becomes ‭128 (10000000). As similar to left rotation, if data is stored using 8 bits, then the right rotation of the data 32(‭‬00100000‬) by 2 becomes 8 (00001000).

#include <stdio.h>

#define INT_BITS 32

#define ROTATE_LEFT(pos, data) ((data << pos)|(data >> (INT_BITS - pos)))

#define ROTATE_RIGHT(pos, data) ((data >> pos)|(data << (INT_BITS - pos)))


int main()
{
    int pos = 2; // Number of rotation

    int data = 32; //data which will be rotate

    printf("%d Rotate Left by %d is ", data, pos);
    printf("%d \n", ROTATE_LEFT(pos, data));

    printf("%d Rotate Right by %d is ",data, pos);
    printf("%d \n", ROTATE_RIGHT(pos, data));

    return 0;
}

 

 

Q) Compute the minimum (min) or maximum (max) of two integers without branching?

We can find the minimum (min) or maximum (max) number without the branching with the help of a bitwise operator.

Let’s assume “a” and “b” are integers numbers and “result” is another integer variable that contains the result of the
computation.

So to compute the minimum number we have to write the below expression.

result = b ^ ((a ^ b) & -(a < b)); // min(a, b)

In above expression,if a < b, then -( a < b) become -1, so it behave like below expression

result = b ^ ((a ^ b) & ~0);

result =  b ^ a ^ b; // b^b is zero

result = a ^ 0; // oring with 0 does not effect

result = a; //minimum number

 

Compute the maximum number we have to write the below expression.

result = a ^ ((a ^ b) & -(a < b)); // max(a, b)

In above expression,if a > b, then -( a > b) become 0, so it behave like below expression

result = a ^ ((a ^ b) & -(0));

result = a ^ 0; // oring with 0 does not effect

result = a; //Maximum number

 

Q) Swap two numbers without using a temporary variable?

Using the EX-OR operator, we can swap two numbers. Here the concept is that EX-OR of two same numbers is zero.

#include <stdio.h>

void SwapTwoNumber(int *a, int *b)
{
    if(*a == *b) // Check if the two addresses are same
        return;
    *a = *a ^ *b;
    *b = *a ^ *b;
    *a = *a ^ *b;
}

int main()
{
    int x = 10;
    int y = 20;


    SwapTwoNumber(&x, &y);

    printf("x = %d and y = %d",x,y);

    return 0;
}

 

Q) Clear all bits from MSB to the ith bit

Here I have supposed data is stored using 8 bits.

let’s assume the ith position is 2.

mask =(1 <<( i+1)); // give you 00001000

so now if we subtract 1 from the mask (mask = mask – 1), then we will get 00000111

Using the mask, now we can clear MSB to ith bits of data (15).

data = data & mask; // Now bits are clear

interview questions on bitwise operators in c

#include <stdio.h>


int main()
{
    unsigned int mask = 0; // mask flag

    unsigned int i = 2; // ith position till u want to clear the bits

    unsigned int data = 15; //value of data


    mask = (1 << (i+1)); //Shift 1 ith position

    mask = mask -1 ; //give us 00000111

    //Now clear all bits from msb to ith position
    data  = data & mask;

    printf("data = %d\n", data);

    return 0;
}

 

Q) Clear all bits from LSB to ith bit

To clear all bits of a data from LSB to the ith bit, we have to perform AND operation between data and mask (flag) having LSB to ith bit 0.

To create a mask, first left-shift 1 (i+1) times.

mask =(1 << (i+1)); // give you 00001000

Now if we minus 1 from that, all the bits from 0 to i become 1 and remaining bits become 0.

mask = mask – 1 ; // give you 00000111

After that perform complement operation on the mask, all the bits from 0 to i become 0 and remaining bits become 1.

mask = ~mask; //give you 11111000

Now just simply perform anding operation between mask and data to get the desired result.

data = data & mask; // Now bits are clear from LSB to ith position

tricky questions on bitwise operators in c

#include <stdio.h>

int main()
{
    unsigned int mask = 0; // mask flag

    unsigned int i = 2; // ith position till u want to clear the bits

    unsigned int data = 15; //value of data


    mask = (1 << (i+1)); //Shift 1 ith position

    mask = mask -1 ; //give us 00000111

    mask = ~mask; //give us 11111000

    //Now clear all bits from msb to ith position
    data  = data & mask;

    printf("data = %d\n", data);

    return 0;
}

 

Q) Multiply a number by 2 using bitwise operation

Left shifting of a data (number) by 1 is equivalent to data*2. In data, every bit is a power of 2, with each shift we are increasing the value of each bit by a factor of 2.

#include <stdio.h>

int main()
{
    unsigned int data = 15; //value of data

    data = data << 1; // equivalent to data * 2

    printf("data = %d\n", data);

    return 0;
}

 

Q) Divide a number by 2 using bitwise operation

Right shifting of a data (number) by 1 is equivalent to data/2. In data, every bit is a power of 2, with each right shift we are reducing the value of each bit by a factor of 2.

#include <stdio.h>

int main()
{

    unsigned int data = 16; //value of data

    data = data >> 1; // equivalent to data/2

    printf("data = %d\n", data);

    return 0;
}

 

Q) Multiply a given Integer with 3.5 using bitwise operation

We know that multiplication is basically an addition, so we can multiply a given integer (data) with 3.5 using the following operation, (2 *data) + data + (data/2).

#include <stdio.h>

int main()
{

    unsigned int data = 10; //value of data

    data = (data<<1) + data + (data>>1);; // equivalent to data * 3.5

    printf("data = %d\n", data);

    return 0;
}

 

Q) How to change endianness?

In the below image, you can see the conversion.

Endianness Conversion

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>


//Function to change the endianess
uint32_t ChangeEndianness(uint32_t u32Value)
{
    uint32_t u32Result = 0;

    u32Result |= (u32Value & 0x000000FF) << 24;
    u32Result |= (u32Value & 0x0000FF00) << 8;
    u32Result |= (u32Value & 0x00FF0000) >> 8;
    u32Result |= (u32Value & 0xFF000000) >> 24;


    return u32Result;
}

int main()
{

    uint32_t u32CheckData  = 0x11223344;
    uint32_t u32ResultData =0;

    u32ResultData = ChangeEndianness(u32CheckData);  //swap the data

    printf("0x%x\n",u32ResultData);

    u32CheckData = u32ResultData;


    u32ResultData = ChangeEndianness(u32CheckData);//again swap the data

    printf("0x%x\n",u32ResultData);

    return 0;

}

 

Q) Swap two nibbles of a byte

A nibble consists of four bits, sometime interviewer asked the question to swap the nibble of a byte. It is a very easy question, here << (left shift) and >> (right shift) operators are used to swap the nibble.

#include <stdio.h>

//Macro to swap nibbles
#define SWAP_NIBBLES(data) ((data & 0x0F)<<4 | (data & 0xF0)>>4)

int main()
{
    unsigned char value = 0x23; //value in hex
  
    printf("0x%x", SWAP_NIBBLES(value)); //print after swapping
  
    return 0;
}

 

Q) How do I get a bit from an integer value in C?

To get the ith bit, perform Anding operation between the ith bit and 1 (1 << i) after that shift the result ith position in right using the right operation.

#include <stdio.h>

//Macro to Get bit from the given position
#define GET_BITS(data, pos) ((data & ( 1 << pos)) >> pos)

int main()
{
    unsigned char value = 16; //value in hex 00010000

    unsigned char position = 1;

    printf("%d\n", GET_BITS(value,position)); //print gets value from the 1th position

    position = 4;

    printf("%d\n", GET_BITS(value,position)); //print gets value from 3rd position


    return 0;
}

 

 

Q) Write the macros to set, clear, toggle and check the bit of a given integer.

 

See the below macro,

  • #define SET_BIT(value, pos) value |= (1U<< pos)
  • #define CLEAR_BIT(value, pos) value &= ~(1U<< pos)
  • #define TOGGLE_BIT(value, pos) value ^= (1U<< pos)
  • #define CHECK_BIT_IS_SET_OR_NOT(value, pos) value & (1U<< pos)

Let see an example to set the bit using the above macro,

#include <stdio.h>

#define SET_BIT(value, pos) value |= (1U<< pos)


int main()
{
    //value
    unsigned int value =0;

    //bit position
    unsigned int pos = 0;

    printf("Enter the value\n");
    scanf("%d",&value);

    printf("Enter the position you want to Set\n");
    scanf("%d",&pos);

    SET_BIT(value,pos);

    printf("\n\n%dth Bit Set Now value will be = 0x%x\n",pos,value);

    return 0;
}

 

Output:

set bit

 

Q) Write MACRO to swap the bytes in 32bit Integer Variable.

I have already written this program in endianness conversion. But here I am creating a Macro for the same.

#include <stdio.h>
#include <inttypes.h>


#define SWAP_BYTES(u32Value) ((u32Value & 0x000000FF) << 24)\
|((u32Value & 0x0000FF00) << 8) \
|((u32Value & 0x00FF0000) >> 8) \
|((u32Value & 0xFF000000) >> 24)


int main()
{

    uint32_t u32CheckData  = 0x11223344;
    uint32_t u32Result = 0;

    u32Result = SWAP_BYTES(u32CheckData);  //swap the data

    printf("0x%x\n",u32Result);

    return 0;
}

byte conversion in c

Q) Swap all odd and even bits

In the above question, you need to swap the even and odd bits. To accomplish the above task you need to first find the even and odd bits then shift these bits. See the below steps,

Let the input number is data (Assuming integer size is 4 bytes),

  1. Get all even bits of data by doing bitwise and (&) of data with 0xAAAAAAAA (data & 0xAAAAAAAA).
  2. Get all odd bits of data by doing bitwise and (&) of data with 0x55555555 (data & 0x55555555).
  3. Right shift all even bits ((data & 0xAAAAAAAA)>>1).
  4. Left shift all odd bits ((data & 0x55555555)<<1).
  5. Combine the value which gets from the left and right operation ((data & 0xAAAAAAAA)>>1 | (data & 0x55555555)<<1).

Example code,

#include <stdio.h>

int main()
{
    int data = 2;

    data = ((data & 0xAAAAAAAA)>>1 | (data & 0x55555555)<<1);

    printf("%d",data);

    return 0;
}

 

Q) Count number of bits to be flipped to convert A to B

In this question, you need to count flipped bits that require to convert A to B. To accomplish this task you need to find the number of bits that are different in A and B.

Suppose, A = 8, B = 7

Binary representation of A => 00001000
Binary representation of B => 00000111

Here we have to flip highlighted four bits of A
to make it B.

 

Algorithm

  1. Calculate XOR of A and B.With the help of XOR, we will discard the common bits and set the bits that are different in numbers A and B.
  2. Count the set bits of the above calculated XOR result.

Example code,

#include <stdio.h>

//function to calculate flipped bits
int CountFlippedBits(int A, int B)
{
    int XorResult = 0;
    int count = 0;

    //Doing Ex-or
    XorResult = (A ^ B);

    //Count set bits
    while (XorResult)
    {
        count += XorResult & 1;
        XorResult >>= 1;
    }

    return count;
}

int main()
{
    int A = 8;
    int B = 7;
    int ret = 0;

    //Function return count of flipped bits
    ret = CountFlippedBits(A,B);

    printf("Flipped Bits = %d\n",ret);

    return 0;
}

 

Output: Flipped Bits = 4

Recommended Post



54 comments

    1. It is techniques to find the larger number without the branching.

      If a > b, then -( a > b) become 0,

      result = a ^ ((a ^ b) & -(a < b)); // max(a, b) result = a ^ ((a ^ b) & -(0)); result = a ^ 0; // OR-ing with 0 does not effect

      result = a; //Maximum number

  1. Hey,
    very nice way explain bitwise operators. looking more interview question and answers like this type examples and keep it up. One small request after done one sample code please try to put output screen short also its better clear it.

  2. hi

    excellent sir..nice way to explanation,,its very helpfull for me.,,,,can you please share more and more programs,,,,,

    thank you

  3. Compute the sign of an integer?

    In the solution, no application of bitwsie opertaors

    It would be good if we can use bitwise operators here

    1. Yes, you can use bit-wise operator but if you also want to check that number is zero or not then this is also a good way. But agree with the bit-wise operation.

  4. It seems that in first solution for program reversing bits of a number MSB will not be reversed.
    int iNumberLopp should be set to INT_BITS (not INT_BITS -1);

  5. I see most of interview questions covered on bit-wise operators. good to have similar posts for ARM, Booting process and linux

Leave a Reply

Your email address will not be published. Required fields are marked *