typedef的一个位域变量 [英] Typedef a bitfield variable

查看:208
本文介绍了typedef的一个位域变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个typedef是1位整数,所以我虽然这个的类型定义INT:1 FLAG; ,但我得到的错误吧,是有没有办法我可以这样做?
谢谢

I want to have a typedef that is 1-bit integer, so I though of this typedef int:1 FLAG; but I'm getting errors with it, is there a way I can do so? Thanks

推荐答案

没有。

在C程序中最小的可寻址东西是的字节字符。结果
A 字符至少为8位长。结果
所以,你不能有一个类型(或任何类型的对象)少于8位。

The smallest addressable "thing" in a C Program is a byte or char.
A char is at least 8 bits long.
So you cannot have a type (or objects of any type) with less than 8 bits.

你可以做的是有一个类型,哪些对象至少占据尽可能多的位作为字符,而忽略大多数的位

What you can do is have a type for which objects occupy at least as many bits as a char and ignore most of the bits

#include <limits.h>
#include <stdio.h>

struct OneBit {
    unsigned int value:1;
};
typedef struct OneBit onebit;

int main(void) {
    onebit x;
    x.value = 1;
    x.value++;
    printf("1 incremented is %d\n", x.value);
    printf("each object of type 'onebit' needs %d bytes (%d bits)\n",
          (int)sizeof x, CHAR_BIT * (int)sizeof x);
    return 0;
}

您可以在上面看到在 ideone 运行code。

You can see the code above running at ideone.

这篇关于typedef的一个位域变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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