My question is how do you convert a UINT32 value to a UINT8 array[4] (C/C++) preferably in a manner independent of endianness? Additionally, how would you reconstruct the UINT32 value from the UINT8 array[4], to get back to where you started?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
You haven't really said what you mean by independent of endianness - it's unclear since the byte array must have some endianness. That said, one of the below must answer your requirements:
Given
UINT32 v
andUINT8 a[4]
:"Host" endian
(use the machine's native byte order):
or:
or:
Big endian
(aka "network order"):
Little endian
E.g. like this:
Edit: added parenthesis (>> seems to have higher precedence than &)
One could also do it with pointers. (This is little endian, but if you use the same reconstruction method it won't matter)
This assigns the value of the uint32 to the 4 bytes after the memory address of the uint8, doing exactly what you need.
To go the other way:
If you don't want to code it yourself, you can use the C library function htonl() to convert the 32-bit int to network byte order. There is also the function ntohl() to convert them back to host order.
Once they're in network byte order, it's simply a matter of accessing the int/long as a byte array.
All in all that's are probably the most portable and tested way of achieving your goal.
use a Union consisting of an Array with 4 time uint8 and an uint32.
So it sorts automatically by c inherent pointer Magic (Arrays are pointers to start of array)