问题描述
我使用的位域工作再上一个浮点数库我试图做出不带FPU微控制器方便地访问。
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__));
问题是,当我试图访问或更改任何它认为分别从末端位域为1,8,23位。而应该是从端23位,则8位,然后最后一个比特。除非我已经完全误解了使用位字段。我想到用包装将解决这个问题,但你可以看到它没有。
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.
任何帮助将是非常美联社preciated。而谷歌搜索不止一次让我有很高的期望,我一直带领这个网站。
Any help would be really appreciated. I have been lead to this site while googling more than once so I have high hopes.
推荐答案
您可能忽略了结构的联合中。
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__));
注意尾数/指数和符号的顺序取决于CPU的一个字节顺序。
Note that the order of mantissa/exponent and sign depends one the endianess of the cpu.
这篇关于是什么在C位域使用的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!