Search code examples
c++vectorcharuint32

Concatenation of vector elements into one 32-bit word


I am trying to concatenate a vector of four elements into a 4-byte word to represent as an uint32_t.

Sorry, I don't have my code, but this is what I am trying to do:

vector v; // each element is a byte, with four elements v[0], v[1], v[2], v[3] concatenate these four elements to form a word (I guess a char[32]?) [0][1][2][3] to use as a uint32_t.

I have tried changing v[0,1,2,3] to strings then appending the strings using loops but for whatever reason, the end results was adding erroneous bits.

Thank you so much for the help everyone!


Solution

  • What you are looking for is bit shifting and bitwise OR, eg:

    std::vector<uint8_t> v;
    // fill v with 4 bytes as needed...
    uint32_t i = (uint32_t(v[X1]) << 24) | (uint32_t(v[X2]) << 16) | (uint32_t(v[X3]) << 8) | uint32_t(v[X4]);
    

    Where X1..X4 are the desired byte indexes in the vector, depending on which endian you want to use for the uint32_t.

    Alternatively, if the vector elements are already in the correct byte order for the endian you want the uint32_t to be in, you can just memcpy() the bytes as-is:

    std::vector<uint8_t> v;
    // fill v with 4 bytes as needed...
    uint32_t i;
    std::memcpy(&i, v.data(), 4);