如何将向量转换为到整数?
我有 vector
归档了二进制数据。比方说,我需要从向量(2 个字节)中获取 2 个项目并将其转换为整数。不使用 C 风格如何做到这一点?
I have vector<unsigned char>
filed with binary data. I need to take, lets say, 2 items from vector(2 bytes) and convert it to integer. How this could be done not in C style?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你不想关心大/小端,你可以使用:
If you don't want to care about big/little endian, you can use:
请使用移位运算符/按位运算。
这里提出的所有基于强制转换/联合的解决方案都是 AFAIK 未定义的行为,并且可能在利用 严格别名(例如 GCC)。
Please use the shift operator / bit-wise operations.
All the solutions proposed here that are based on casting/unions are AFAIK undefined behavior, and may fail on compilers that take advantage of strict aliasing (e.g. GCC).
你可以这样做:
You may do:
v[0]*0x100+v[1]
v[0]*0x100+v[1]
那么,另一种方法是包装对 memcpy 的调用:
extract 函数模板也适用于 double、long int、float 等。
本例中没有尺寸检查。我们假设在每次调用 extract 之前 v 实际上有足够的元素。
祝你好运!
Well, one other way to do it is to wrap a call to memcpy:
The extract function template also works with double, long int, float and so on.
There are no size checks in this example. We assume v actually has enough elements before each call to extract.
Good luck!
“不是C风格”是什么意思?使用按位运算(移位和或)来使其工作并不意味着它是“C 风格!”
有什么问题:
int t = v[0]; t = (t << 8) | v[1];
?what do you mean "not in C style"? Using bitwise operations (shifts and ors) to get this to work does not imply it's "C style!"
what's wrong with:
int t = v[0]; t = (t << 8) | v[1];
?