简体   繁体   中英

how to convert a uint32 variable to 2 unit 16 variables?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM