c - C语言中的位数据类型
问题描述
我想用 c 语言创建一个位数据类型。我尝试使用带有位域的结构来创建它
struct bittype {
unsigned int value:1;
};
typedef struct bittype bit;
但问题是我必须使用像
bit statusVariable;
statusVariable.value = 1;
我怎样才能直接定义一个变量,
bit statusVariable;
statusVariable = 1;
解决方案
位不能单独寻址,只有字节。
struct bittype {
unsigned int value:1;
};
typedef struct bittype bit;
您的结构的大小将等于或大于unsigned int
如果你定义
bit eightBits[8];
它不会定义位数组,只定义结构数组。它的大小8*sizeof(bit)
至少为8*sizeof(unsigned int)
.
如果你想定义一个只能有 or 值的对象0
,1
最好的方法是使用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
推荐阅读
- java - 为什么我不能为方法返回的对象引用赋值?
- excel - 适用于 Windows 键的 Application.OnKey
- angular - 如何修复Angular中的“无法设置只有getter的[object Object]的属性userInfo $”错误
- racket - DrRacket - 显示列表中高于平均水平的所有值
- applescript - 使用 Automator 通过 QuickTime 将 wav 转换为 m4a
- excel - 完全除数的“n”的最大幂
- c# - 在 .NetCore 的 EF 核心中禁用和启用表触发器
- python-3.x - 如何在我的文件夹中找到 ._6182142_V1.csv?
- php - 从查询中获取特定字段(不起作用)未定义变量:fetch_data
- spring - Liquibase 正在尝试执行已执行的脚本