简体   繁体   中英

How to convert any value to vector<bool>

I'm trying to convert any object to std::vector<bool> (representing bits set in memory to strore the object).

So, for uint16_t(0x1234) , I want to get std::vector<bool> ‭0001001000110100 ‬. And for float(3.14f) , which is ‭ 0x4048F5C3‬ in memory, I want to get std::vector<bool> ‭‭01000000010010001111010111000011 ‬.

Based on this post , I tried this:

template<typename T>
std::vector<bool> val2Array(T val)
{
    size_t count = sizeof(T)*CHAR_BIT;
    std::vector<bool> result( count );
    for (size_t i = 0; i < count; i++)
    {
        T temp = 1 << (count - i - 1);
        if ( val & temp )
            result[i] = true;
        else
            result[i] = false;
    }

    return result;
}

This works fine, but I get an error when T is not numerical ( float ), due to << operator.

Is there any other way to convert any value to a std::vector<bool> ? I found lots of code showing how to convert std::vector<bool> to a value but not the way around.

What you described reminds me of reinterpret_cast . You just want to see the bits, regardless of their underlying interpretation, so reinterpret those bits as something that std::bitset can accept and put them in your vector.

#include <bitset>
#include <vector>
#include <iostream>

constexpr int CHAR_BIT = 8;

template<typename T>
std::vector<bool> val2Array(T val)
{
    uintmax_t i = reinterpret_cast<uintmax_t&>(val);
    auto bits = std::bitset<sizeof(uintmax_t)*CHAR_BIT>(i);

    size_t count = sizeof(T)*CHAR_BIT;
    std::vector<bool> result( count );

    for(size_t i = 0; i < count; ++i)
        result[count-i-1] = bits[i];

    return result;
}

int main()
{
    auto i = uint16_t(0x1234);
    auto iv = val2Array(i);
    for(auto&& e : iv) std::cout << e;
    std::cout << std::endl;


    auto f = float(3.14f);
    auto fv = val2Array(f);
    for(auto&& e : fv) std::cout << e;
    std::cout << std::endl;
}

output

0001001000110100
01000000010010001111010111000011

For converting the bitset to a vector , I found this post that cites a blogpost for a bitset_iterator that might be usefull

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