Home > Back-end >  how to convert a uint32 variable to 2 unit 16 variables?
how to convert a uint32 variable to 2 unit 16 variables?

Time:08-04

I have a vector of uint32 variables that has no meaning for me . but first 16 bits and second 16 bits of them have meaning . Then i need to separate it indexes to 2 uint16 variables in c . what should i do for this issue ?

CodePudding user response:

Here is an implementation.

vector<uint32_t> a = {/*your data goes here*/};
vector<uint16_t> mostSignificantBits, leastSignificantBits;
for(uint32_t i : a) {
    mostSignificantBits.push_back((uint16_t)(i >> 16));
    leastSignificantBits.push_back((uint16_t)i);
}

Simply casting it will take the 16 least significant bits.

To retrieve the most significant bits, we use right shift.

CodePudding user response:

You have to split them as uint32 and them force conversion.

std::pair<uint16_t, uint16_t> split(uint32_t var) {
    return {static_cast<uint16_t>(var >> 16),
            static_cast<uint16_t>(var & 0xffff)};
}

std::vector<std::pair<uint16_t, uint16_t>> split_vector(std::vector<uint32_t> v) {
    std::vector<std::pair<uint16_t, uint16_t>> r;
    for (const auto& e: v) {
        r.emplace_back(split(e));
    }
    return r;
}
  • Related