Search code examples
cbit-manipulationbitgeneric-programming

Swap every two bits of an unknown variable type


I need to swap every two adjacent bits as a generic operation which will do so for every variable type given.

I thought of the needed masks and operations for every single byte:

(var & 0x55) << 1 | (var & 0xAA) >> 1

But how do I make this apply for let's say an integer? Do I need to create an array of sizeof(int) unsigned chars with the above masks and apply the operation that way?


Solution

  • You can do this byte by byte (the same as char by char).

    For example:

    int n = 0xAA55A55A;
    unsigned char *p = (unsigned char *) &n;
    
    for (; p < (unsigned char *) &n + sizeof(n); p++)
       *p = (*p & 0x55) << 1 | (*p & 0xAA) >> 1;