本文实例讲述了C++二进制翻转的方法,将常用的几种解决方法罗列出来供大家比较选择。具体如下:
首先来看看一个相对笨拙的算法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#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); } |
下面这个翻转程序相对上面实例而言简洁高效:
1
2
3
4
5
6
7
8
9
10
11
|
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; } |
下面这个反转程序比较容易理解:
1
2
3
4
5
6
7
|
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; } |
最后这个超牛的反转程序简直碉堡了。。。
1
2
3
4
5
6
|
unsigned char codeTable[16]={0x00, 0x08, 0x04, 0x0c, 0x02, 0x0a, 0x06, 0x0e, 0x01, 0x09, 0x05, 0x0d, 0x03, 0x0b, 0x07, 0x0f}; unsigned char swapBinary3(unsigned char data) { return ((codeTable[data >> 4]) | (codeTable[data & 0x0f] << 4)); } |
希望本文所述对大家C++程序算法设计的学习有所帮助。