gpt4 book ai didi

c - 我如何制作一个 25 位宽的无符号整数和一个 bool 位?

转载 作者:太空宇宙 更新时间:2023-11-04 06:45:43 25 4
gpt4 key购买 nike

我希望使用位字段,当我可以将它们都压缩成 4 个字节时,没有理由为什么这样的东西会占用 5 个字节,毕竟,我的 25 位整数中有 7 个不需要的位,但是, avr-gcc 在编译时给我一个错误-

error: width of ‘prettybignum’ exceeds its type
unsigned int prettybignum : 25;

此外,我还有另一个错误-

useless storage class specifier in empty declaration [-Werror]
};

我的结构看起来像这样:

typedef struct tinyBitmap // Should take 4 bytes per instance
{
unsigned int prettybignum : 25;
bool yesorno : 1;
};

我的结构定义有问题吗?

编辑:很抱歉写下它应该是 3 个字节。我的意思是说 4 个字节。我知道那是怎么回事,我错了。无论哪种方式,是的,我正在尝试将所有内容压缩到尽可能少的字节中,我昨天刚刚发现了位域,我真的很高兴发现了它们。我试图在没有抽象的情况下手动完成这类事情(使用位移位将 8 个 bool 值存储在一个 uint 中),我希望 C 能够抽象出所有这些疯狂行为并使其易于在我的程序中管理和访问(不需要特殊的辅助函数)

最佳答案

error: width of ‘prettybignum’ exceeds its type
unsigned int prettybignum : 25;

C 允许实现在整数类型的大小方面有一定的自由度。类型 unsigned int 可以窄到 16 位。如果你必须至少有 25 个值位,或者如果你想确保你尽可能简约,那么请使用 long int 类型,然后包含 stdint.h 并使用类型uint_least32_t

useless storage class specifier in empty declaration [-Werror]
};

编译器指出您使用的是类型别名声明的形式,但没有指定任何标识符作为别名。这样的标识符(或多个标识符)通常位于 struct 声明的右括号和整个声明的终止分号之间,这就是编译器向您显示这些的原因。这通常是警告,而不是错误,但您还要求编译器将所有警告视为错误。

您可以通过以下任一方式清除它

  • 删除无用的(在目前编写的声明中)typedef 关键字。这对于声明结构类型不是必需的;相反,它用于定义类型别名。

  • 指定一个标识符作为 struct tinyBitmap 类型的别名。

My struct looks something like this:

typedef struct tinyBitmap // Should take 3 bytes per instance
{
unsigned int prettybignum : 25;
bool yesorno : 1;
};

另外,考虑到你的声明......

typedef struct tinyBitmap // Should take 3 bytes per instance

... 表明你似乎有一个误解。三个字节仅提供 24 位,因此如果您的结构包含 25 位位域,则它必须至少占用 32 位(对于 CHAR_BIT == 8,这几乎肯定是您的情况)。

总的来说,您有多种选择,但假设目标是最小存储量,那么这是您最好的两个选择:

  • 没有 typedef,因此该类型将被引用为 struct tinyBitmap

    #include <stdint.h>

    struct tinyBitmap {
    uint_least32_t prettybignum : 25;
    bool yesorno : 1;
    };
  • 使用 typedef,这样类型不仅可以作为 struct tinyBitmap 引用,还可以作为您选择的其他标识符引用,例如作为“我的位图”:

    #include <stdint.h>

    typedef struct tinyBitmap {
    uint_least32_t prettybignum : 25;
    bool yesorno : 1;
    } my_bitmap;

为了说明 typedef 不是结构定义的一部分,我观察到后者可以等价地写成两个单独的语句,而且更清楚:

#include <stdint.h>

struct tinyBitmap {
uint_least32_t prettybignum : 25;
bool yesorno : 1;
};

typedef struct tinyBitmap my_bitmap;

关于c - 我如何制作一个 25 位宽的无符号整数和一个 bool 位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com