2

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!

JonnyCplusplus
  • 881
  • 3
  • 12
  • 22

5 Answers5

4

The basic principler here would be:

int x = 0; 
for(uint8_t i : v)
{
   x <<= 8; 
   x |= i;
}
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

Not tested:

int time = 0;
for (int i:v) time = time << 8 + i;
hivert
  • 10,579
  • 3
  • 31
  • 56
1

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.

David Foerster
  • 1,461
  • 1
  • 14
  • 23
1

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 );
mocj
  • 1,456
  • 1
  • 9
  • 9
0

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];
Annie Kim
  • 895
  • 6
  • 17