首页 > 解决方案 > C语言中的位数据类型

问题描述

我想用 c 语言创建一个位数据类型。我尝试使用带有位域的结构来创建它

struct bittype {
    unsigned int value:1;
};
typedef struct bittype bit;

但问题是我必须使用像

bit statusVariable;
statusVariable.value = 1;

我怎样才能直接定义一个变量,

bit statusVariable;
statusVariable = 1;

标签: cgcc

解决方案


位不能单独寻址,只有字节。

struct bittype {
    unsigned int value:1;
};
typedef struct bittype bit;

您的结构的大小将等于或大于unsigned int

如果你定义

bit eightBits[8]; 

它不会定义位数组,只定义结构数组。它的大小8*sizeof(bit)至少为8*sizeof(unsigned int).

如果你想定义一个只能有 or 值的对象01最好的方法是使用bool类型,因为bool只能有值0或者1尽管分配了值

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    bool x = 1;
    printf("%d\n", x);
    x = 100;
    printf("%d\n", x);
    x = -100;
    printf("%d\n", x);
    x = 0;
    printf("%d\n", x);
}

将输出

1
1
1
0

推荐阅读