我正在努力将系统从python转换为c ++。我需要能够在c ++中执行通常通过使用Python的 struct.unpack (将二进制字符串解释为数值)执行的操作。对于整数值,我能够使用 stdint.h 中的数据类型得到这个(排序)工作:
I am working on translating a system from python to c++. I need to be able to perform actions in c++ that are generally performed by using Python's struct.unpack (interpreting binary strings as numerical values). For integer values, I am able to get this to (sort of) work, using the data types in stdint.h:
struct.unpack("i", str) ==> *(int32_t*) str; //str is a char* containing the data这适用于小尾数法二进制字符串,在大端的二进制字符串上失败。基本上,我需要一个等价的使用struct.unpack中的> 标记:
This works properly for little-endian binary strings, but fails on big-endian binary strings. Basically, I need an equivalent to using the > tag in struct.unpack:
struct.unpack(">i", str) ==> ???请注意,如果有更好的方法来做到这一点,但是,我不能使用c + + 11,也不能使用Boost以外的任何第三方库。我还需要能够解释浮动和双精度,如 struct.unpack(> f,str)和 struct.unpack (> d,str),但是当我解决这个问题的时候我会得到这个。
Please note, if there is a better way to do this, I am all ears. However, I cannot use c++11, nor any 3rd party libraries other than Boost. I will also need to be able to interpret floats and doubles, as in struct.unpack(">f", str) and struct.unpack(">d", str), but I'll get to that when I solve this.
strong>我应该指出,我的机器的字节序在这种情况下是无关紧要的。我知道在我的代码中接收的比特流将始终是big-endian,这就是为什么我需要一个解决方案,将始终覆盖big-endian的情况。 BoBTFish在评论中指出的文章似乎提供了一个解决方案。
NOTE I should point out that the endianness of my machine is irrelevant in this case. I know that the bitstream I receive in my code will ALWAYS be big-endian, and that's why I need a solution that will always cover the big-endian case. The article pointed out by BoBTFish in the comments seems to offer a solution.
推荐答案每次解开字符串一个字节。
Unpack the string one byte at a time.
unsigned char *str; unsigned int result; result = *str++ << 24; result |= *str++ << 16; result |= *str++ << 8; result |= *str++;更多推荐
处理c ++中的字节序
发布评论