C++二進制翻轉實例剖析。本站提示廣大學習愛好者:(C++二進制翻轉實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是C++二進制翻轉實例剖析正文
本文實例講述了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++法式算法設計的進修有所贊助。