Converting a UINT32 value into a UINT8 array[4]

不打扰是莪最后的温柔 提交于 2019-11-27 16:08:09

问题


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?


回答1:


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 and UINT8 a[4]:

"Host" endian

(use the machine's native byte order):

UINT8 *vp = (UINT8 *)&v;
a[0] = vp[0];
a[1] = vp[1];
a[2] = vp[2];
a[3] = vp[3];

or:

memcpy(a, &v, sizeof(v));

or:

*(UINT32 *)a = v;

Big endian

(aka "network order"):

a[0] = v >> 24;
a[1] = v >> 16;
a[2] = v >>  8;
a[3] = v;

Little endian

a[0] = v;
a[1] = v >>  8;
a[2] = v >> 16;
a[3] = v >> 24;



回答2:


E.g. like this:

UINT32 value;
UINT8 result[4];

result[0] = (value & 0x000000ff);
result[1] = (value & 0x0000ff00) >> 8;
result[2] = (value & 0x00ff0000) >> 16;
result[3] = (value & 0xff000000) >> 24;

Edit: added parenthesis (>> seems to have higher precedence than &)




回答3:


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.




回答4:


One could also do it with pointers. (This is little endian, but if you use the same reconstruction method it won't matter)

uint32 in = 0x12345678;
uint8 out[4];
*(uint32*)&out = in;

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:

uint8 in[4] = {0x78, 0x56, 0x34, 0x12};
uint32 out;
out = *(uint32*)&in



回答5:


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)



来源:https://stackoverflow.com/questions/6499183/converting-a-uint32-value-into-a-uint8-array4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!