1バイトデータの任意のビットを任意のビットへ動かす

#include <stdio.h>
//#include <sstream>
//#include <bitset>
//#include <string>
//#include <iostream>
//using namespace std;

/*// 1バイトデータを2進数の数「字」として表示するための函数
void printByteAsBin(uint8_t oneByte){
    std::stringstream s;
    s << std::bitset<8>(oneByte);
    std::string binStr = s.str();
    //binStr.insert(4, " ");
    //binStr = "0b " + str;
    std::cout << binStr << std::endl;
}*/

/*// 1バイトデータを2進数の数「字」として表示するための函数。<sstream>、<bitset>を使わない場合。
void printByteAsBin(uint8_t oneByte){
    std::string binStr = "";
    //binStr.reserve(30);
    //std::cout << binStr.capacity() << std::endl;
    uint8_t mask  = 128; // 0b 1000 0000;
    for(int i=0; i<8; i++){
        (oneByte & mask) ? (binStr += "1") : (binStr += "0");
        mask >>= 1;
    }
    //binStr.insert(4, " ");
    //binStr = "0b " + binStr;
    std::cout << binStr << std::endl;
}*/

// 1バイトデータを2進数の数「字」として表示するための函数。
void printByteAsBin(uint8_t oneByte){
    char binStr[8];
    uint8_t mask = 128; // 0b 1000 0000;
    for(int i=0; i<8; i++){
        (oneByte & mask) ? (binStr[i] = '1') : (binStr[i] = '0');
        mask >>= 1;
    }
    printf("%s\n", binStr);
}

/*
// 1バイトデータの任意のビットを任意のビットへ動かすための函数
unsigned char byte2pos(unsigned char oneByte, unsigned char *pos){
   return 
   (((oneByte & 128) >> 7) << pos[0]) |
   (((oneByte &  64) >> 6) << pos[1]) |
   (((oneByte &  32) >> 5) << pos[2]) |
   (((oneByte &  16) >> 4) << pos[3]) |
   (((oneByte &   8) >> 3) << pos[4]) |
   (((oneByte &   4) >> 2) << pos[5]) |
   (((oneByte &   2) >> 1) << pos[6]) |
   (((oneByte &   1)     ) << pos[7]); 
}
*/

// 1バイトデータの任意のビットを任意のビットへ動かすための函数
uint8_t byte2pos(uint8_t oneByte, uint8_t *pos){
    uint8_t mask   = 128; // 0b 1000 0000;
    uint8_t sorted = 0;
    for(int i=0; i<8; i++){
        if(oneByte & mask){
            sorted |= (1 << pos[i]);
        }
        mask >>= 1;
    }
    return sorted;
}

int main(){
    uint8_t oneByte = 0b11011011; // この1バイトデータの
    printByteAsBin(oneByte);

    uint8_t pos[8] = {4,5,6,7,0,1,2,3};  // ビット[7]をビット[4]へ、ビット[6]をビット[5]へ、...... 動かす。

    uint8_t a = byte2pos(oneByte, pos);
    printByteAsBin(a);

    return 0;
}

f:id:ti-nspire:20190122070829p:plain