简体   繁体   中英

int64_t to std::vector<bool> using only `std`

Suppose that x is an int64_t . How can I efficiently convert it to a std::vector<bool> with 64 elements, one for each bit of x , without using other libraries than std ?

Edit: std::bitset<64> is not an option to me, for instance because I need to call push_back and std::find on it.

The makeVec function below will allow you to turn a 64-bit value into a boolean vector:

#include <iostream>
#include <vector>
#include <cstdint>

std::vector<bool> makeVec(int64_t x) {
    std::vector<bool> retVal;
    uint64_t mask = 1ULL << 63;
    for (int i = 0; i < 64; ++i) {
        retVal.push_back((static_cast<uint64_t>(x) & mask) == 0 ? false : true);
        mask >>= 1;
    }
    return retVal;
}

int main() {
    auto vec = makeVec (42);
    for (int i = 0; i < 64; ++i) {
        std::cout << (vec[i] ? '1' : '0');
    }
    std::cout << '\n';
}

However, you may find it easier to use a bitset for this, so your code becomes a simpler:

#include <iostream>
#include <bitset>

int main() {
    auto vec = std::bitset<64>(42);
    for (int i = 63; i >= 0; --i) {
        std::cout << vec[i];
    }
    std::cout << '\n';
}

The one difference you'll note there is the reversal of the bit positions. With a bitset, position zero is the least significant bit, so you have to adjust for that.


If you wanted a similar ordering (the zero index being the least significant bit) in the vector solution, that would just be a matter of changing a couple of lines:

std::vector<bool> makeVec(int64_t x) {
    std::vector<bool> retVal;
    uint64_t mask = 1;                 // This one ...
    for (int i = 0; i < 64; ++i) {
        retVal.push_back((static_cast<uint64_t>(x) & mask) == 0 ? false : true);
        mask <<= 1;                    // ... and this one.
    }
    return retVal;
}

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