简体   繁体   中英

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.

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.

In Standard C++ it's not possible to do this reliably. 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.

However you can do the opposite: declare an int and then fill in the bytes:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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