Search code examples
c++vectorbyteunsigned-char

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?


Solution

  • 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.