Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create and fill a 10 bits set from two 8 bits characters

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading