Sunday, November 1, 2020

C programming - Count number of bits to be flipped to convert A to B

From :- https://aticleworld.com/interview-questions-on-bitwise-operators-in-c/

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;
}

C programming - Swap all odd and even bits

From  - https://aticleworld.com/interview-questions-on-bitwise-operators-in-c/ 

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;
}