Q:

Swap all odd and even bits

0

Swap all odd and even bits

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Count number of bits to be flipped to convert A to... >>
<< Write MACRO to swap the bytes in 32bit Integer Var...