C++二进制翻转实例分析

2025-05-29 0 29

本文实例讲述了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++程序算法设计的学习有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++二进制翻转实例分析 https://www.kuaiidc.com/107912.html

相关文章

发表评论
暂无评论