我有一个2-D整数数组(8x8),其中每个“行”包含一个接收的消息。我感兴趣的是将这个数组的元素,incomingMessageBuffers [1] [0:7]映射到一个具有已定义位域的结构中,这可能比使用掩码和移位方法更快。我知道位域排序依赖于编译器,但无论我想知道为什么我看到观察到的行为,因为我认为它与这个事实无关。
我想要映射到MYSTRUCT的内存
- incomingMessageBuffer [1][0:7]
0. 0x1544
1. 0x0000
2. 0x0008
3. 0x3400
4. 0x0012
5. 0x8100
6. 0x0000
7. 0x0000
MYSTRUCT定义:
struct MYSTRUCT{
unsigned int PACKET0:16;
unsigned int PACKET1:16;
unsigned int PACKET2:16;
unsigned char PACKET3_LOW:8;
unsigned int MYINTEGER:16;
unsigned char PACKET4_HIGH:8;
unsigned char PACKET5_LOW:8;
unsigned char MYBIT:1;
unsigned char EXTRABITS:3;
unsigned char MYNIBBLE:4;
unsigned int PACKET6:16;
unsigned int PACKET7:16; }
我的映射代码和所需结果的示例:
volatile struct MYSTRUCT *Message
Message = &incomingMessageBuffer[1][0];
myInteger = (Message->MYINTEGER);
myBit = (Message->MYBIT);
myNibble = (Message->MYNIBBLE);
Expected values:
myInteger = 0x1234
myBit = 0x01;
myNibble = 0x08;
相反,它正确映射到PACKET0,1和2,但以下成员分配不正确。根据我对这种定义的惯例的理解......
struct
{
type [member_name] : width ;
};
type定义了member_name类型(即PACKET6,MYBIT等),其中如果类型大小大于宽度,则member_name中的额外高位将用零填充。我想这是不正确的,因为我没有看到预期的值被分配,除非我定义我的结构:
struct MYSTRUCT_2{
unsigned int PACKET0:16;
unsigned int PACKET1:16;
unsigned int PACKET2:16;
unsigned char PACKET3_LOW:8;
unsigned long int MYINTEGER:16; //Notice long int here
unsigned char PACKET4_HIGH:8;
unsigned char PACKET5_LOW:8;
unsigned char MYBIT:1;
unsigned char EXTRABITS:3;
unsigned char MYNIBBLE:4;
unsigned int PACKET6:16;
unsigned int PACKET7:16;
}
然后使用结构成员的掩码分配我的变量:
volatile struct MYSTRUCT *Message
Message = &incomingMessageBuffer
myInteger = (Message->MYINTEGER)&0xFFFF
myBit = (Message->MYBIT)&0x01
myNibble = (Message->MYNIBBLE)&0x0F
那么,为什么将MYINTEGER声明为无符号 long int会导致按位映射正确赋值,如果它只是定义了MYINTEGER的大小?
非常感谢任何帮助。
答案 0 :(得分:0)
我认为问题可能是由于我的第一个结构中的整数定义未对齐。对齐将需要整数的第一位定义为16的倍数。
这样......
struct MYSTRUCT{
unsigned int PACKET0:16;
unsigned int PACKET1:16;
unsigned int PACKET2:16;
unsigned char PACKET3_LOW:8;
unsigned char PACKET4_HIGH:8;
unsigned int MYINTEGER:16;
unsigned char PACKET5_LOW:8;
unsigned char MYBIT:1;
unsigned char EXTRABITS:3;
unsigned char MYNIBBLE:4;
unsigned int PACKET6:16;
unsigned int PACKET7:16; }
...因为MYINTEGER在两个字符定义之后出现,每个字符定义映射到结构中的8位。然而,使用相同的逻辑,我不明白为什么将它声明为长整数将解决问题。