(E-Mail Removed) wrote:

> Is there any easy way to reverse the order of the bits in a byte in

> C++?

>

> (i.e. 00000001 becomes 10000000)

>
The one true way is to recognize that reversing any sequence of bits

involves only splitting it into two parts and returning a value whose

upper half is the reverse of the original lower half and whose lower

half is the reverse of the original upper half. Like this:

#include <limits>

#include <iomanip>

#include <iostream>

using std::numeric_limits;

using std::cout; using std::hex; using std::showbase;

using std::internal; using std::setw;

template <unsigned n> struct reverser_imp

{

static inline unsigned reverse(unsigned val, unsigned mask)

{

mask >>= (n/2);

return reverser_imp<n/2>::reverse((val >> (n/2)) & mask, mask)

| (reverser_imp<n/2>::reverse(val & mask, mask) << (n/2));

}

};

template <> struct reverser_imp<1>

{

static inline unsigned reverse(unsigned val, unsigned)

{

return val;

}

};

inline unsigned reverse(unsigned val)

{

return reverser_imp<numeric_limits<unsigned char>::digits>::

reverse(val, numeric_limits<unsigned char>::max());

}

void show_reversed(unsigned val)

{

cout.fill('0');

cout << hex << showbase << internal;

cout << setw(4) << val << ": "

<< setw(4) << reverse(val) << '\n';

}

int main()

{

show_reversed(0x0f);

show_reversed(0x80);

show_reversed(0x40);

show_reversed(0xC0);

return 0;

}

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and

Reference." For more information about this book, see

www.petebecker.com/tr1book.