将数组
int a[] = {0 , 1 , 2 , 3 , 4 , 5 , 6 , 7};
进行位逆置变换变为
{0 , 4 , 2 , 6 , 1 , 5 , 3 , 7};
变换前二进制表示为:
000 , 001 , 010 , 011 , 100 , 101 , 110 , 111
变换后:
000 , 100 , 010 , 110 , 001 , 101 , 011 , 111
代码如下:
#include <iostream>
using namespace std;
// the array size must be is 2 of pow
// such as : 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7
// binary express is :000 , 001 , 010 , 011 , 100 , 101 , 110 , 111
// the reserve bit is : 000 , 100 , 010 , 110 , 001 , 101 , 011 , 111
// 0 , 4 , 2 , 6 , 1 , 5 , 3 , 7
template<size_t N>
void ReserveBit( int( &n )[N] )
{
int size = log( N ) / log( 2 );
for( int index = 0; index < N; index++ )
{
int answer = 0;
int bit = 1;
for( int i = 0; i < size; i++ )
{
answer <<= 1;
if( n[index] & bit )
{
answer |= 1;
}
bit <<= 1;
}
n[index] = answer;
}
}
int main( void )
{
int a[] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 };
ReserveBit( a );
int size = sizeof( a ) / sizeof( a[0] );
for( int i = 0; i < size; i++ )
{
cout << i << ": " << a[i] << endl;
}
system( "pause" );
return 0;
}
结果如下: