Click to See Complete Forum and Search --> : Easy way to swap to bits in a Byte?


Michael Menne
February 28th, 2003, 04:58 PM
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

Doctor Luz
February 28th, 2003, 06:01 PM
supposing x is at i position (begining from right) and y is at j position and i<>j. Calling the byte b

swap=b-(b&(1<<i))-(b&(1<<j))+((1&(b>>i))<<j)+((1&(b>>j))<<i);

Test it please, because here is too late and my brain asks for sweet dreams.

dude_1967
March 1st, 2003, 10:56 AM
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.

:)



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;
}

Michael Menne
March 1st, 2003, 04:57 PM
Thanks for the help!

I now got a good and very fast way of swapping bits in bytes as well as in (unsigned) integers. Your solution is working, Doctor Luz, though the one I found is a little faster and in my opinion easier to understand. Nevertheless your's was a good starting point.
Basically I'm first checking if the two values are equal, if not I'm using a xor operation to swap them.

Thats the function I'm now using:


UINT&nbsp;u&nbsp;=&nbsp;279836;
int&nbsp;x&nbsp;=&nbsp;1;
int&nbsp;y&nbsp;=&nbsp;4;

if(((u&(1<<x))!=0)&nbsp;!=&nbsp;((u&(1<<y))!=0))
{
&nbsp;&nbsp;&nbsp;&nbsp;u&nbsp;^=&nbsp;((1<<x)&nbsp;|&nbsp;(1<<y));
}



-Menne