And if 100001 is stored in a string, you can use the reverse() algorithm :
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string binary = "1010000001";
cout << binary << endl;
reverse(binary.begin(), binary.end());
cout << binary << endl;
return 0;
}
Main Topics
Browse All Topics





by: EarthQuakerPosted on 2003-02-05 at 07:57:22ID: 7883349
Well there is different ways...
Let's say you say the binary representation of a number, then you can use this function :
inline unsigned char reverse_byte(unsigned char byte)
{
return
((byte&1)<<7) +
((byte&2)<<5) +
((byte&4)<<3) +
((byte&8)<<1) +
((byte&16)>>1) +
((byte&32)>>3) +
((byte&64)>>5) +
((byte&128)>>7);
}
unsigned char c = 5; // c is 00000101
cout << reverse_byte(c) << endl;
And if you need it for a short, int or bigger you can write a template function which handle it :
template <class T>
T reverse_bits(T nNumber)
{
T tmp;
unsigned char *in = (unsigned char*) &nNumber;
unsigned char *out = (unsigned char*) &tmp;
for (int i=0, j=sizeof(T)-1; i<sizeof(T);++i,--j)
out[i] = reverse_byte(in[j]);
return tmp;
}