Easy way to swap two bits in a Byte?
I'm currently trying to figure out an easy way to swap to bits in a Byte variable.
So for example I want to swap the x and y in 0101 0x1y, so that it becomes 0101 0y1x. The other bits shouldn't be changed.
Currently I'm using if statements, but I just imagine that there is an easier (faster) way to do it with bit operations. (xor, &, |).
Or am I totally wrong and there is only the way with the if statments?
Pherhaps somebody does know it an is so friendly to help me.
Sincerely,
Michael Menne
Use templates and simple algorithms
I usually use templates and simple, easy-to-read algorithms for these types of operations. The templates allow for typesafe use with several data-types. You might find some interesting ideas in the implementation below.
Sincerely, Chris.
NOTE: Edited about 30 minutes after posting, code was corrected.
:)
Code:
typedef unsigned char BYTE;
typedef unsigned long int DWORD;
template <typename T> const T t_bit(const int bit)
{
return static_cast<T>(1) << bit;
}
template <typename T> const T swap(const T t, const int i, const int j)
{
T tt = t;
tt &= ~t_bit<T>(i); // mask out bit i
tt &= ~t_bit<T>(j); // mask out bit j
const T ti = t_bit<T>(i) & t; // isolate bit i
const T tj = t_bit<T>(j) & t; // isolate bit j
// Swap the bits
if(ti)
{
tt |= t_bit<T>(j);
}
if(tj)
{
tt |= t_bit<T>(i);
}
return tt;
}
int main(int argc, char* argv[])
{
BYTE b;
b = ::swap<BYTE>(0x0F, 0, 7);
b = ::swap<BYTE>(0xF0, 0, 7);
DWORD d;
d = ::swap<DWORD>(0x0000000F, 0, 31);
d = ::swap<DWORD>(0xF0000000, 0, 31);
return 1;
}