JonnyCplusplus
JonnyCplusplus

Reputation: 881

convert subset of vector<uint8_t> to int

I am having trouble figuring out how to convert an vector of hex values to a decimal long int.

    vector<uint8_t>v;

    v.push_back(0x02);
    v.push_back(0x08);
    v.push_back(0x00);
    v.push_back(0x04);
    v.push_back(0x60);
    v.push_back(0x50);
    v.push_back(0x58);
    v.push_back(0x4E);
    v.push_back(0x01);
    v.push_back(0x80);

//How would I achieve this:
    long time =  0x00046050584E0180; //1,231,798,102,000,000

How would I get elements 2-9 for the vector v into an long int like represented above with the long 'time'.

Thanks!

Upvotes: 2

Views: 4566

Answers (5)

David Foerster
David Foerster

Reputation: 1540

Since std::vector contains its data in a memory vector, you can use a pointer cast, e. g.:

vector<uint8_t> v;
assert(v.size() >= 2 + sizeof(long)/sizeof(uint8_t));
long time = *reinterpret_cast<const long*>(&v[2]);

Make sure, the vector contains enough data though, and beware of different endianness types.

Upvotes: 1

mocj
mocj

Reputation: 1486

You can of course do this algorithmically with the appropriately defined function:

long long f( long long acc, unsigned char val )
{
   return ( acc << 8 ) + val;
}

the value is computed by:

#include <numeric>

long long result = std::accumulate( v.begin() + 2, v.end(), 0ll, f );

Upvotes: 1

Mats Petersson
Mats Petersson

Reputation: 129464

The basic principler here would be:

int x = 0; 
for(uint8_t i : v)
{
   x <<= 8; 
   x |= i;
}

Upvotes: 4

Annie Kim
Annie Kim

Reputation: 905

My solution is as below and I've already tested. You may have a try.

long long res = 0;
for (int i = 2; i < 10; ++i)
    res = (res << 8) + v[i];

Upvotes: 0

hivert
hivert

Reputation: 10667

Not tested:

int time = 0;
for (int i:v) time = time << 8 + i;

Upvotes: 1

Related Questions