Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

c++ - Converting a UINT32 value into a UINT8 array[4]

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...