简体   繁体   English

转换向量的子集 <uint8_t> 到int

[英]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. 我在弄清楚如何将十六进制值的向量转换为十进制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'. 如何将向量v的元素2-9变为长整数,如上面用长'时间'表示的那样。

Thanks! 谢谢!

The basic principler here would be: 这里的基本原则是:

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

Not tested: 未经测试:

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

Since std::vector contains its data in a memory vector, you can use a pointer cast, eg: 由于std::vector其数据包含在内存向量中,因此可以使用指针强制转换,例如:

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. 确保矢量包含足够的数据,但要注意不同的字节序类型。

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 );

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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM