简体   繁体   中英

Convert size_t to vector<unsigned char>

I want to convert size_t to vector of unsigned chars. This vector is defined as 4 bytes. Could anybody suggest a suitable way to do that?

Once you've reconciled yourself to the fact that your std::vector is probably going to have to be bigger than that - it will need to have sizeof(size_t) elements - one well-defined way is to access the data buffer of such an appropriately sized vector and use ::memcpy :

size_t bar = 0; /*initialise this else the copy code behaviour is undefined*/
std::vector<uint8_t> foo(sizeof(bar)); /*space must be allocated at this point*/
::memcpy(foo.data(), &bar, sizeof(bar));

There is an overload of data() that returns a non- const pointer to the data buffer. I'm exploiting this here. Accessing the data buffer in this way is unusual but other tricks (using unions etc.) often lead to code whose behaviour is, in general, undefined.

By "convert", I'll assume you mean "copy", since vector will allocate and own its memory. You can't just give it a pointer and expect to use your own memory.

An efficient way to do so which avoids two-stage construction (that causes initialization of the array with zero) is to do this:

auto ptr = reinterpret_cast<uint8_t*>(&the_size);
vector<uint8_t> vec{ptr, ptr + sizeof(size_t)};

Note that sizeof(size_t) is not required to be 4. So you shouldn't write your code assuming that it is.

You could write a generic converter using std::bitset

template <typename T>
std::vector<unsigned char> Type_To_Bit_Vector(T type, char true_char, char false_char){

    //convert type to bitset
    std::bitset<sizeof(type)*8> bset(type);

    //convert bitset to vector<unsigned char>
    std::vector<char> vec;
    for(int i = 0 ; i < bset.size() ; i++){
        if (bset[i]){
            vec.push_back(true_char);
        }else{
            vec.push_back(false_char);
        }
    }

    return vec;
}

You could then get a desired vector representation like so:

auto vec = Type_To_Bit_Vector(size_t(123),'1','0');

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