简体   繁体   English

如何在C中定义1位大小的数据类型?

[英]How can I define a datatype with 1 bit size in C?

我想为C中的布尔值true / false定义数据类型。是否有任何方法可以定义要声明为boolean的1位大小的数据类型?

Maybe you are looking for a bit-field: 也许您正在寻找一个位域:

struct bitfield
{
     unsigned b0:1;
     unsigned b1:1;
     unsigned b2:1;
     unsigned b3:1;
     unsigned b4:1;
     unsigned b5:1;
     unsigned b6:1;
     unsigned b7:1;
};

There are so many implementation-defined features to bit-fields that it is almost unbelievable, but each of the elements of the struct bitfield occupies a single bit. 位域有许多实现定义的功能,这几乎令人难以置信,但是struct bitfield每个元素都占据一个位。 However, the size of the structure may be 4 bytes even though you only use 8 bits (1 byte) of it for the 8 bit-fields. 但是,该结构的大小可能为4字节,即使您仅将8位(1字节)用于8位字段。

There is no other way to create a single bit of storage. 没有其他方法可以创建单个存储。 Otherwise, C provides bytes as the smallest addressable unit, and a byte must have at least 8 bits (historically, there were machines with 9-bit or 10-bit bytes, but most machines these days provide 8-bit bytes only — unless perhaps you're on a DSP where the smallest addressable unit may be a 16-bit quantity). 否则,C提供字节作为最小的可寻址单元,并且字节必须至少具有8位(从历史上看,有些机器具有9位或10位字节,但是如今大多数机器仅提供8位字节,除非可能您在DSP上,其中最小的可寻址单元可能是16位)。

Try this: 尝试这个:

#define bool int
#define true 1
#define false 0

In my opinion use a variable of type int . 我认为使用类型为int的变量。 That is what we do in C. For example: 这就是我们在C语言中所做的。例如:

int flag=0;
if(flag)
{
    //do something
}
else
{
    //do something else
}

EDIT: 编辑:

You can specify the size of the fields in a structure of bits fields in bits. 您可以在位结构中以位为单位指定字段的大小。 However the compiler will round the type to at the minimum the nearest byte so you save nothing and the fields are not addressable and the order that bits in a bit field are stored is implementation defined. 但是,编译器会将类型四舍五入到最接近的最小字节,以便您不保存任何内容,并且这些字段不可寻址,并且在位字段中存储位的顺序是由实现定义的。 Eg: 例如:

struct A {
  int a : 1; // 1 bit wide
  int b : 1;
  int c : 2; // 2 bits
  int d : 4; // 4 bits
};

Bit-fields are only allowed inside structures. 位字段仅允许在结构内部使用。 And other than bit-fields, no object is allowed to be smaller than sizeof(char). 除位字段外,不允许任何对象小于sizeof(char)。

The answer is _Bool or bool. 答案是_Bool或bool。

C99 and later have a built-in type _Bool which is guaranteed to be large enough to store the values 0 and 1. It may be 1 bit or larger, and it is an integer. C99和更高版本具有内置类型_Bool,该类型必须保证足够大以存储值0和1。它可以是1位或更大,并且是整数。

They also have a library include which provides a macro bool which expands to _Bool, and macros true and false that expand to 1 and 0 respectively. 它们还有一个库include,它提供了一个扩展为_Bool的宏bool,以及分别扩展为1和0的true和false宏。

If you are using an older compiler, you will have to fake it. 如果使用的是较旧的编译器,则必须伪造它。

[edit: thanks Jonathan] [编辑:谢谢乔纳森]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM