简体   繁体   English

C ++字节数组转换为int

[英]C++ byte array to int

Now there is a unsigned char bytes[4] and I've already known that the byte array is generated from an int in C++. 现在有一个unsigned char bytes[4] ,我已经知道字节数组是从C ++中的int生成的。 How can I convert the array back to int ? 如何将数组转换回int

I've already known that the byte array is generated from an int in C++. 我已经知道字节数组是从C ++中的int生成的。

It is crucial to know how the array is generated from an int. 知道如何从int生成数组至关重要。 If the array was generated by simply copying the bytes on the same CPU , then you can convert back by simply copying: 如果数组是通过简单地在同一CPU上复制字节生成的,则可以通过简单地复制来转换回:

int value;
assert(sizeof value == sizeof bytes);
std::memcpy(&value, bytes, sizeof bytes);

However, if the array may follow another representation than what your CPU uses (for example, if you've received the array from another computer, over the network), then you must convert the representation. 但是,如果该阵列可能遵循了CPU使用的其他表示形式(例如,如果您是通过网络从另一台计算机接收到该阵列的),则必须转换该表示形式。 In order to convert the representation, you must know what representation the source data follows. 为了转换表示形式,您必须知道源数据遵循的表示形式。

Theoretically, you would need to handle different sign representations, but in practice, 2's complement is fairly ubiquitous. 从理论上讲,您需要处理不同的符号表示形式,但实际上2的补码是相当普遍的。 A consideration that is actually relevant in practice is the byte-endianness. 在实践中实际上相关的一个考虑因素是字节序。

You can do that using std::memcpy() : 您可以使用std::memcpy()做到这一点:

#include <iostream>
#include <cstring>

int main() {
    unsigned char bytes[4]{ 0xdd, 0xcc, 0xbb, 0xaa };

    int value;
    std::memcpy(&value, bytes, sizeof(int));

    std::cout << std::hex << value << '\n';
}

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

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