代码之家  ›  专栏  ›  技术社区  ›  Hani Gotc

从两个8位字符创建并填充一个10位集合

c++
  •  1
  • Hani Gotc  · 技术社区  · 4 年前

    我们有两个角色 a b的 8 我们想要在10位集合中编码的位。我们要做的是抢先一步 8. 字里行间 A. 将它们放入10位集合的前8位。那就只拿第一个吧 2 字里行间 b 然后填满剩下的。

    enter image description here

    问题: 我是否需要移位8位以连接其他2位?

    // Online C++ compiler to run C++ program online
    #include <iostream>
    #include <bitset>
    
    struct uint10_t {
        uint16_t value : 10;
        uint16_t _     : 6;
    };
    
    uint10_t hash(char a, char b){
        uint10_t hashed;
        // Concatenate 2 bits to the other 8
        hashed.value = (a << 8) + (b & 11000000);
        return hashed;
    }
    
    int main() {
       uint10_t hashed = hash('a', 'b');
       std::bitset<10> newVal = hashed.value;
       std::cout << newVal << "  "<<hashed .value << std::endl;
       return 0;
    }
    

    谢谢@Scheff的猫。我的猫打招呼 enter image description here

    1 回复  |  直到 4 年前
        1
  •  1
  •   Scheff's Cat    4 年前

    我是否需要移位8位以连接其他2位?

    然而,在OPs公开的代码中,两位 b 不见了。

    应该是:

    hashed.value = (a << 8) + ((b & 0xc0) >> 6);
    

    hashed.value = (a << 8) + ((b & 0b11000000) >> 6);`
    

    MCVE on coliru :

    // Online C++ compiler to run C++ program online
    #include <iostream>
    #include <bitset>
    
    struct uint10_t {
        uint16_t value : 10;
        uint16_t _     : 6;
    };
    
    uint10_t hash(char a, char b){
        uint10_t hashed;
        // Concatenate 2 bits to the other 8
        hashed.value = (a << 8) + ((b & 0b11000000) >> 6);
        return hashed;
    }
    
    int main() {
       uint10_t hashed = hash('a', 'b');
       std::bitset<10> newVal = hashed.value;
       std::cout << newVal << "  "<<hashed .value << std::endl;
       return 0;
    }
    

    输出:

    0100000001  257