Swap Odd and Even Bits

Write a C function to swap all odd and even bits in an unsigned integer. Bit positions 0, 2, 4, ... are considered even bits, and positions 1, 3, 5, ... are odd bits. Ex input: 10101010 (in binary), Expected O/P: 01010101. It may look simple at first, well, like just outputting its complement, but is that right? What if the input is 11010010? How would you proceed with this question?
2 Replies
brotherjoons
brotherjoons5mo ago
Complement works, right? Ah, but you have to limit the length of the values to be complemented. (& 0xff, etc...)
nour_oud
nour_oud5mo ago
C
C
#include <stdio.h>

unsigned int swapOddEvenBits(unsigned int num) {
// Masks for even and odd bits
unsigned int evenMask = 0b10101010101010101010101010101010;
unsigned int oddMask = 0b01010101010101010101010101010101;

// Extract even and odd bits
unsigned int evenBits = num & evenMask;
unsigned int oddBits = num & oddMask;

// Swap even and odd bits
evenBits >>= 1;
oddBits <<= 1;

// Combine swapped even and odd bits
return evenBits | oddBits;
}

int main() {
// Example input: 10101010
unsigned int num = 0b10101010;

// Print input
printf("Input: %08x\n", num);

// Swap odd and even bits
unsigned int result = swapOddEvenBits(num);

// Print output
printf("Output: %08x\n", result);

return 0;
}
C
C
#include <stdio.h>

unsigned int swapOddEvenBits(unsigned int num) {
// Masks for even and odd bits
unsigned int evenMask = 0b10101010101010101010101010101010;
unsigned int oddMask = 0b01010101010101010101010101010101;

// Extract even and odd bits
unsigned int evenBits = num & evenMask;
unsigned int oddBits = num & oddMask;

// Swap even and odd bits
evenBits >>= 1;
oddBits <<= 1;

// Combine swapped even and odd bits
return evenBits | oddBits;
}

int main() {
// Example input: 10101010
unsigned int num = 0b10101010;

// Print input
printf("Input: %08x\n", num);

// Swap odd and even bits
unsigned int result = swapOddEvenBits(num);

// Print output
printf("Output: %08x\n", result);

return 0;
}