A general function for bit swapping which you can use:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Swap bits in an integer number
// pos1, pos2 are the start positions (= the bit numbers) from the right to the left in theNumber where the bits
// should be interchanged.
// shiftcount is the number of bits that will be affected
//
// Original code: https://www.geeksforgeeks.org/swap-bits-in-a-given-number/
//
template <typename iint>
iint SwapBits(iint theNumber, unsigned int pos1, unsigned int pos2, unsigned int shiftCount)
{
iint bitMask = ((iint)1 << shiftCount) - 1; // Create the AND bitmask
iint set1 = (theNumber >> pos1) & bitMask; // Move all bits of first set to rightmost side
iint set2 = (theNumber >> pos2) & bitMask; // Do the same with the second
iint exor = (set1 ^ set2); // XOR the two sets
exor = (exor << pos1) | (exor << pos2); // Put the xor'ed bits back to their original positions
iint result = theNumber ^ exor; // XOR the 'exor' with the original number so that the two sets are swapped
return result;
}
For debug purposes you can use this function to print numbers in binary:
//////////////////////////////////////////////////////////////////////////////////////////////
// Function to get a binary representation of an integer number as a string for printf
//
// Use it like this:
// short num = 0x8008; // You can use (unsigned) char, short, int, int64_t etc.
// printf("%s\n", NumToBinary(num)); // Prints 1000000000001000
//
template <typename num>
char *NumToBinary(num theNumber, char *binBuf = NULL)
{
static char asBinary[9]; // Max int64 plus terminating zero
int i;
char *p = asBinary; // Buffer pointer
if (binBuf) // User supplied buffer present
p = binBuf; // Use it instead of the static buffer
int bitLen = sizeof(num) << 3; // Number of bits in theNumber, 2^3 = 8
uint64_t bit = (uint64_t)0x1 << (bitLen - 1); // Start with MSB
for (i = 0; i < bitLen; i++)
{
p[i] = ((theNumber & bit) == bit) ? '1' : '0';
bit >>= 1;
}
p[i] = '\0';
return p;
}