What's the correct way of using bitfields in C?

試著忘記壹切 提交于 2019-12-05 23:13:47

问题


I am using bitfields to get easy access on a float library I am trying to make for a microcontroller with no FPU.

The problem is that I can't seem to make it work with bitfields. Take a look:

typedef struct
{
   union{
    unsigned long mantissa: 23;
    unsigned long exponent: 8;
    unsigned long sign: 1;
    float all;

      };

}_float __attribute__((__packed__));

The problem is that when I try to access or change anything it considers the bitfields as 1,8,23 bits from the end respectively. While it should be 23 bits from the end, then 8 bits and then the last bit. Unless I have totally misunderstood the use of bitfields. I thought that using packed would solve the problem but as you can see it didn't.

Any help would be really appreciated. I have been lead to this site while googling more than once so I have high hopes.


回答1:


You might be missing a struct inside your union.

typedef struct
{
    union{
       struct {
           unsigned long mantissa: 23;
           unsigned long exponent: 8;
           unsigned long sign: 1;
       } float_parts;
       float all;
    };
}_float __attribute__((__packed__));

Note that the order of mantissa/exponent and sign depends one the endianess of the cpu.




回答2:


The problem is that it is a union. It should be 'struct'.




回答3:


If you are on a glibc platform you can take a look on the ieee754.h header file. It takes care about the endianess stuff. If not it's still probably worth to take a look on it.



来源:https://stackoverflow.com/questions/587348/whats-the-correct-way-of-using-bitfields-in-c

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