C++二進位翻轉執行個體分析_C 語言

來源:互聯網
上載者:User

本文執行個體講述了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++程式演算法設計的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.