Interview Questions and Answers :: Ciena
Home > Experience Archives > Ciena > Interview Question Set > Discussion
35. Write a code to swap every two bits in a byte.
Input: 10 01 11 00 Output: 01 10 11 00
Answer:
#include
unsigned int swapBitsInPair(unsigned int x)
{
/*
extracts the high bit position and shifts it to the low bit position.
similarly extracts the low bit from each pair and shifts it to the high bit position.
The two parts are then combined using bitwise OR
*/
return ((x & 0b10101010) >> 1) | ((x & 0b01010101) << 1);
}
int main()
{
unsigned int x = 156;
printf("%d", swapBitsInPair(x));
return 0;
}
Ram
8 Apr, 2018 3:25 PM
#include
unsigned int swapBitsInPair(unsigned int x)
{
/*
extracts the high bit position and shifts it to the low bit position.
similarly extracts the low bit from each pair and shifts it to the high bit position.
The two parts are then combined using bitwise OR
*/
return ((x & 0b10101010) >> 1) | ((x & 0b01010101) << 1);
}
int main()
{
unsigned int x = 156;
printf("%d", swapBitsInPair(x));
return 0;
}
unsigned int swapBitsInPair(unsigned int x)
{
/*
extracts the high bit position and shifts it to the low bit position.
similarly extracts the low bit from each pair and shifts it to the high bit position.
The two parts are then combined using bitwise OR
*/
return ((x & 0b10101010) >> 1) | ((x & 0b01010101) << 1);
}
int main()
{
unsigned int x = 156;
printf("%d", swapBitsInPair(x));
return 0;
}
Report Error
Report Error
Please Login First Click Here