#include <iostream>
void showBits(const unsigned char ch) {
for (int i = 1 << 8 - 1; i > 0; i = i / 2) {
(ch & i) ? std::cout << "1" : std::cout << "0";
}
}
int swap2Bits(unsigned char num, const unsigned char firstPos, const unsigned char secondPos) {
unsigned int firstBit = (num >> firstPos) & 1;
unsigned int secondBit = (num >> secondPos) & 1;
unsigned int xorBit = (firstBit ^ secondBit);
xorBit = (xorBit << firstPos) | (xorBit << secondPos);
return num ^ xorBit;
}
int main()
{
unsigned char ch = 29;
showBits(ch);
unsigned char result = swap2Bits(ch, 1, 2);
std::cout << "\n";
showBits(result);
}
/*
run:
00011101
00011011
*/