在 C 中使用位域的正确方法是什么?

发布于 2024-07-14 08:17:15 字数 501 浏览 6 评论 0原文

我正在使用位字段来轻松访问我正在尝试为没有 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

触ぅ动初心 2024-07-21 08:17:15

您可能缺少联合内的结构。

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

请注意,尾数/指数和符号的顺序取决于 cpu 的字节顺序。

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.

梦太阳 2024-07-21 08:17:15

问题是它是一个联盟。 应该是“结构”。

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

雨落□心尘 2024-07-21 08:17:15

如果您使用的是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文