我正在使用位字段来轻松访问我正在尝试为没有 FPU 的微控制器制作的浮点库。
问题是我似乎无法使其与位字段一起使用。 看一下:
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 位,然后是最后一位。 除非我完全误解了位域的使用。 我认为使用 packed 可以解决问题,但正如你所看到的,它没有解决。
任何帮助将非常感激。 我不止一次在谷歌搜索时被引导到这个网站,所以我抱有很高的期望。
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.
发布评论
评论(3)
您可能缺少联合内的结构。
请注意,尾数/指数和符号的顺序取决于 cpu 的字节顺序。
You might be missing a struct inside your union.
Note that the order of mantissa/exponent and sign depends one the endianess of the cpu.
问题是它是一个联盟。 应该是“结构”。
The problem is that it is a union. It should be 'struct'.
如果您使用的是 glibc 平台,您可以查看 ieee754.h 头文件。 它关心字节序的事情。 如果没有的话,可能仍然值得一看。
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.