vendredi 31 juillet 2020

How to store into and read back multiple number values on an `uint16_t` using bitwise manipulation?

Using bitwise operations, is it possible to package and read back the following set of values into an uint16_t variable? I think yes but I am trying to figure out how using a sample program.

Lets say following is the set of values I want to package into an uint16_t.

unsigned int iVal1 = 165 // which is 8 bits
unsigned int iVal2 = 28  // which is 5 bits
unsigned int iVal3 = 3   // which is 2 bits
bool bVal = true;        // which can stored in 1 bit if we use 0 for true and 1 for false

Following is my program which aims to write in the values and needs to read back. How can write and read the values back using C++ 11?

#include <iostream>

uint16_t Write(unsigned int iVal1, unsigned int iVal2, unsigned int iVal3, bool bVal) {
    // Is this technique correct to package the 3 values into an uint16_t?
    return static_cast<uint16_t>(iVal1) + static_cast<uint16_t>(iVal2) + static_cast<uint16_t>(iVal3) + static_cast<uint16_t>(bVal);
}

unsigned int ReadVal1(const uint16_t theNumber) {
    // How to read back iVal1
}

unsigned int ReadVal2(const uint16_t theNumber) {
    // How to read back iVal2
}

unsigned int ReadVal3(const uint16_t theNumber) {
    // How to read back iVal3
}

bool ReadVal4(const uint16_t theNumber) {
    // How to read back bVal
}

int main() {
    unsigned int iVal1 = 165; // which is 8 bits
    unsigned int iVal2 = 28;  // which is 5 bits
    unsigned int iVal3 = 3;   // which is 2 bits
    bool bVal = true;        // which can stored in 1 bit if we use 0 for true and 1 for false

    const uint16_t theNumber = Write(iVal1, iVal2, iVal3, bVal);

    std::cout << "The first 8 bits contain the number: " << ReadVal1(theNumber) << std::endl;
    std::cout << "Then after 8 bits contain the number: " << ReadVal2(theNumber) << std::endl;
    std::cout << "Then after 2 bits contain the number: " << ReadVal3(theNumber) << std::endl;
    std::cout << "Then after 1 bit contains the number: " << ReadVal4(theNumber) << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire