简体   繁体   English

如何从数组向后读取十六进制字符并将其转换为int

[英]How to read hex characters from an array backwards and convert to an int

Say I have an array such as: 说我有一个数组,如:

unsigned char data[2] = { 0x00, 0x20 }; 无符号字符数据[2] = {0x00,0x20};

and I want to get the integer value of all the hex values read backwards, so 0200 would be the hex value which would be 512 in decimal. 我想获得所有十六进制值的整数值,这些值是向后读取的,因此十六进制值0200将是十进制的512。 How would you go about doing this in c++? 您将如何使用C ++进行此操作? I read other posts about using sstream but I am not sure how I would get the stream to read the values backwards. 我读过其他有关使用sstream的文章,但我不确定如何获取流以向后读取值。

First thing - these aren't hex or decimal values. 第一件事-这些不是十六进制或十进制值。 They become that when you print them. 当您打印它们时,它们就会变成那个。 They are binary. 它们是二进制的。 sstream deals with string streams. sstream处理字符串流。 Nothing here refers to strings of text. 这里没有什么是指字符串。

Second thing - what you shouldn't do. 第二件事-你不应该做的。 Don't create a union with unsigned short [] or a reinterpret_cast , and then a bit shift. 不要使用unsigned short []reinterpret_cast创建联合,然后再进行一点移位。 It's unclean, endian dependent, and if you have a lot of data and are performance critical there are better ways. 它是不干净的,依赖于字节序,如果您有大量数据并且对性能至关重要,则有更好的方法。 If not: 如果不:

  i = 0; while(i + 1 < length) { uint16_t value; value = (uint16_t)data[i++]; value |= (uint16_t)data[i++] << 8; ... } 

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

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