简体   繁体   English

C ++-将byte [4]存储在一个int中

[英]c++ - store byte[4] in an int

I want to take a byte array with 4 bytes in it, and store it in an int. 我想要一个包含4个字节的字节数组,并将其存储在一个int中。

For example (non-working code): 例如(非工作代码):

unsigned char _bytes[4];
int * combine;
_bytes[0] = 1;
_bytes[1] = 1;
_bytes[2] = 1;
_bytes[3] = 1;
combine = &_bytes[0];

I do not want to use bit shifting to put the bytes in the int, I would like to point at the bytes memory and use them as an int if possible. 我不想使用移位将字节放入int中,我想指向字节存储器,并在可能的情况下将它们用作int。

In Standard C++ it's not possible to do this reliably. 在Standard C ++中,不可能可靠地执行此操作。 The strict aliasing rule says that when you read through an expression of type int , it must actually designate an int object (or a const int etc.) otherwise it causes undefined behaviour. 严格的别名规则表示,当您读取类型为int的表达式时,它实际上必须指定一个int对象(或const int等),否则会导致未定义的行为。

However you can do the opposite: declare an int and then fill in the bytes: 但是,您可以执行相反的操作:声明一个int然后填写字节:

int combine;
unsigned char *bytes = reinterpret_cast<unsigned char *>(&combine);
bytes[0] = 1;
bytes[1] = 1;
bytes[2] = 1;
bytes[3] = 1;

std::cout << combine << std::endl;

Of course, which value you get out of this depends on how your system represents integers. 当然, 从中获得哪个值取决于系统如何表示整数。 If you want your code to use the same mapping on different systems then you can't use memory aliasing; 如果要让代码在不同的系统上使用相同的映射,则不能使用内存别名。 you'd have to use an equation instead. 您必须改用方程式。

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

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