Reputation: 881
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
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
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
Reputation: 129464
The basic principler here would be:
int x = 0;
for(uint8_t i : v)
{
x <<= 8;
x |= i;
}
Upvotes: 4
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