位域结构分配意外的行为 [英] Bit fields struct assignment unexpected behaviour

查看:89
本文介绍了位域结构分配意外的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么,但如预期的那样位字段赋值不工作。也许仅仅是一个愚蠢的事情,但我没能找到问题。

任何帮助都欢迎。

  typedef结构A {
    unsigned char型A1:1;
    unsigned char型A2:3;
    unsigned char型A3:2;
    unsigned char型A4:2;
} __attribute __((包装))MYSTRUCT;诠释主(){
    MYSTRUCT D组;
    d.a1 = 0;
    d.a2 = 2;
    d.a3 = 1;
    d.a4 = 2;    无符号字符* VAL =(无符号字符*)和D;    的printf(%02X \\ n,* VAL);
    的printf(%02X \\ N的sizeof(HOLA));    出口(0);
}

返回的输出:

  94
01

期望的输出:

  26
01


解决方案

几乎一切关于位域的实现定义。尤其位的一个单位的顺序。


  

(C99,6.7.2.1p10)的单位(高阶到低阶或低阶到高阶)内的位域的分配顺序是实现定义的。


在您的实现中,位存储在一个单位LSB(最低显著位)第一,而不是MSB(最显著位)首先你所期望的。

你有什么是:

  [A1.0] [A2.0] [A2.1] [A2.2] [A2.0] [A3.1] [a4.0] [A4。 1]
   0 0 1 0 1 0 0 1
 位0 - 7位 LSB - MSB

这是 0x94的如果您认为最左边的位是最显著位。

I don't know why but the bit fields assignment is not working as expected. Probably is just an stupid thing, but I've not been able to locate the problem.

Any help is more than welcome.

typedef struct  a {
    unsigned char a1 :1;
    unsigned char a2 :3;
    unsigned char a3 :2;
    unsigned char a4 :2;
} __attribute__((packed)) mystruct;

int main() {
    mystruct d;
    d.a1 = 0;
    d.a2 = 2;
    d.a3 = 1;
    d.a4 = 2;

    unsigned char *val = (unsigned char*) &d;

    printf("%02X \n", *val);
    printf("%02X \n", sizeof(hola));

    exit(0);
}

returned output:

94
01

expected output:

26
01

解决方案

Nearly everything about bit-fields is implementation defined. And particularly the order of bits in a unit.

(C99, 6.7.2.1p10) "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined."

On your implementation, the bits are stored in a unit lsb (least significant bit) first and not msb (most significant bit) first as you would expect.

What you have is:

[a1.0] [a2.0] [a2.1] [a2.2] [a2.0] [a3.1] [a4.0] [a4.1] 
   0      0      1      0      1      0      0      1
 bit 0                     -                      bit 7

 lsb                       -                      msb

which is 0x94 if you consider the left most bit is the least significant bit.

这篇关于位域结构分配意外的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆