是否有可能创建一个长度位在C数据类型 [英] Is it possible to create a data type of length one bit in C

查看:238
本文介绍了是否有可能创建一个长度位在C数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Esentially我想创建一个数据类型 uint1_t 。是,即使可能吗?

Esentially I want to create a data type uint1_t. Is that even possible?

我知道布尔数据类型的大小是一个字节。但是布尔值只需要一个位。因此,没有本质Ç只使用一个位的布尔?如果是,那么它有什么作用与其他七人。以8位,其中一个就足够了,似乎空间这样的浪费。

I know the size of the bool data type is one byte. But boolean values only need one bit. So does C essentially only use one bit for bool? If yes, then what does it do with the other seven. Using eight bits where one is sufficient seems such a waste of space.

推荐答案

这是不是真的可以创建占用一个位一个类型。用C的最小可寻址单元是(这是通过定义一个字节,通常,但不是必须的,8位长,它可能会更长,但不允许在标准C小于8位)。

It is not really possible to create a type that occupies one bit. The smallest addressable unit in C is the char (which is by definition one byte and usually, but not necessarily, 8 bits long; it might be longer but isn't allowed to be shorter than 8 bits in Standard C).

您可以用接近它:

typedef _Bool uint1_t;

#include <stdbool.h>
typedef bool uint1_t;

但它会占用(至少)一个字节,即使一个布尔变量只存储值0或1,真实。你也可以使用一个位域:

but it will occupy (at least) one byte, even though a Boolean variable only stores the values 0 or 1, false or true. You could also use a bit-field:

typedef struct
{
    unsigned int x : 1;
} uint1_t;

但也将占据(至少)一个字节,你需要使用 .X 来访问值。

这篇关于是否有可能创建一个长度位在C数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆