最小的数据类型 - 我可以定义一位变量吗? [英] Smallest data type - can I define a one bit variable?

查看:24
本文介绍了最小的数据类型 - 我可以定义一位变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要一位来表示我的数据 - 1 或 0.在 C 中这样做的最佳方法是什么?正常"数据类型太大.

I need only one bit to represent my data - 1 or 0. What is the best way to do so in C? The "normal" data types are too large.

推荐答案

你可以创建

typedef struct foo
{
    unsigned x:1;
} foo;

您告诉编译器您将只使用一位 x.

Where you have told the compiler that you'll only be using one bit of x.

但是由于结构包装安排(C 标准有意灵活,以便编译器可以根据机器架构进行优化),结果很可能仍然占用与常规 unsigned 一样多的内存空间foo 的数组不必按位连续.

But due to structure packing arrangements (the C standard is intentionally flexible in order that compilers can optimise according to the machine architecture), it may well turn out that this still occupies as much space in memory as a regular unsigned and an array of foos doesn't have to be bitwise contiguous.

这篇关于最小的数据类型 - 我可以定义一位变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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