This article describes the C + + binary Flip method, the commonly used several solutions listed for everyone to compare the choice. Specifically as follows:
Let's take a look at a relatively clumsy algorithm:
#include <iostream>
using namespace std;
void printbinary (unsigned char str, int size = 1)
{
int flag = 0x01;
for (int i = 0; i < size; i++)
{for
(int i = 0; i < 8; i++)
{
if (str & (0x01 << (7-i)) )
cout << "1";
else
cout << "0";
}
cout << Endl;;
}}
unsigned char myswap (unsigned char data)
{
unsigned char flag = 0x01;
for (int i = 0, j = 7; I < J; i++, j--)
{
Int. right = data & (0x01 << i);
int left = data & (0x01 << j);
Data &= ~ (0x01 << j);
Data &= ~ (0x01 << i);
int dist = j-i;
Data |= (right << Dist);
Data |= (left >> dist);
}
return data;
}
void main (void)
{
char source=0x07;
int i;
Printbinary (source, 1);
unsigned char result = Myswap (source);
Printbinary (result);
}
The following flip program is simple and efficient relative to the above example:
unsigned char swapbinary (unsigned char data)
{
int sign = 1;
unsigned char result = 0;
for (int i = 0; I <= 7; i++)
{result
= (data & (sign << i)) >> i) << (7-i);
} return result
;
}
The following reverse procedure is easier to understand:
unsigned char swapBinary2 (unsigned char data)
{
data= (data & 0xf0) >> 4) | (Data & 0x0f) << 4);
Data= ((Data & 0xCC) >> 2) | (Data & 0x33) << 2);
Data= ((Data & 0xAA) >> 1) | (Data & 0x55) << 1);
return data;
}
In the end, this Super Cow reversal program is a bunker ...
unsigned char codetable[16]={0x00, 0x08, 0x04, 0x0c, 0x02, 0x0a, 0x06, 0x0e, 0x01, 0x09, 0x05, 0x0d, 0x03, 0x0b, 0x07, 0x0 f};
unsigned char swapBinary3 (unsigned char data)
{return
(Codetable[data >> 4]) | (Codetable[data & 0x0f] << 4);
}
I hope this article is helpful to the learning of C + + program algorithm design.