简体   繁体   中英

Read all vector elements as one integer in C++

I have this deque and this vector:

std::deque<uint8_t> Time(3);
std::vector<uint8_t> deque_buffer(3);

I do some push_backs :

Time.push_back(1);
Time.push_back(2);
Time.push_back(3);

I copy the data to the vector

for(int i=0; i<3; i++)
{
    deque_buffer.at(i) = Time.at(i);
}

I want to read all the vector data and store it into an int . Meaning I want 0x010203 to be interpreted as 66051 . How do I do it?

Here is what you can do: (sample code on how to "merge" vector elements).

#include <iostream>
#include <vector> 
using namespace std;

int main()
{


    vector<unsigned char> vec = {1,2,3};
    int res = 0;

    for (const auto &val:vec)
    {
        res = (res << 8 ) | val;
    }

    printf ("0x%x\n",res);
    printf ("%d\n",res);
    return 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