在我的 C++ 程序中,我有一个包含四个 unsigned char
成员的结构
struct msg
{
unsigned char zero; unsigned char one; unsigned char two; unsigned char three;
}
并创建了一个结构体数组
msg myMsg[4] = {{0x11,0x22,0xAA,0xCC},{...},{...},{...}};
现在在函数中我想返回这个数组的索引作为 unsigned int
unsigned int procMsg(int n){
return myMsg[n]; // of course this is worng
}
值如:0xCCAA2211
最佳答案
你可以使用移位:
uint32_t little_endian;
uint32_t big_endian;
//...
big_endian = myMsg[0].zero << 24
| myMsg[0].one << 16
| myMsg[0].two << 8
| myMsg[0].three;
little_endian = myMsg[0].three << 24
myMsg[0].two << 16
myMsg[0].one << 8
myMsg[0].zero;
如您所见,对于多字节整数,有两种一般顺序:Big Endian 和 Little Endian。 Big Endian 的最高有效字节 (MSB) 在前。 Little Endian 的最低有效字节 (LSB) 在前。
一般来说,上述方法比使用循环更有效。
关于C++ 将四个无符号字符转换为一个无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53289526/