Home > Enterprise >  Create and fill a 10 bits set from two 8 bits characters
Create and fill a 10 bits set from two 8 bits characters

Time:04-16

We have 2 characters a and b of 8 bits that we want to encode in a 10 bits set. What we want to do is take the first 8 bits of character a put them in the first 8 bits of the 10 bits set. Then take only the first 2 bits of character b and fill the rest.

enter image description here

QUESTION: Do I need to shift the 8 bits in order to concatenate the other 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;
}

Thanks @Scheff's Cat. My cat says Hi enter image description here

CodePudding user response:

Do I need to shift the 8 bits in order to concatenate the other 2?

Yes.

However, in OPs exposed code, the shift of the two bits of b is missing.

It should be:

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

or

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

Output:

0100000001  257
  •  Tags:  
  • c
  • Related