手机
当前位置:查字典教程网 >编程开发 >C语言 >C++二进制翻转实例分析
C++二进制翻转实例分析
摘要:本文实例讲述了C++二进制翻转的方法,将常用的几种解决方法罗列出来供大家比较选择。具体如下:首先来看看一个相对笨拙的算法:#includeu...

本文实例讲述了C++二进制翻转的方法,将常用的几种解决方法罗列出来供大家比较选择。具体如下:

首先来看看一个相对笨拙的算法:

#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); }

下面这个翻转程序相对上面实例而言简洁高效:

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; }

下面这个反转程序比较容易理解:

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; }

最后这个超牛的反转程序简直碉堡了。。。

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++程序算法设计的学习有所帮助。

【C++二进制翻转实例分析】相关文章:

C++中const的实现机制深入分析

使用map实现单词转换的实例分析

OpenCV 2.4.3 C++ 平滑处理分析

基于c++强制类型转换的(总结)详解

从汇编看c++中变量类型的深入分析

C++多态的实现及原理详细解析

深入C++实现函数itoa()的分析

opencv 做人脸识别 opencv 人脸匹配分析

C++中返回指向函数的指针示例

C++中关于Crt的内存泄漏检测的分析介绍

精品推荐
分类导航