如何制作一个位数组?

时间:2017-03-03 10:30:17

标签: c bit bit-fields

我想创建一个int位字段数组,其中每个int都有一位,这意味着所有数字都是1或0,我该怎么编码呢?

我试过

struct bitarr {
    int arr : 1[14];
};

但是这并没有编译,我也不认为这是方式

1 个答案:

答案 0 :(得分:2)

你不能做这些位的数组。相反,为您的位创建单个16位变量,然后您可以i[myindex]访问它,而不是以bitsVariable & (1 << myindex)访问它。

要设置位,您可以使用:

bitsVariable |= 1 << myindex;

要清除位,您可以使用:

bitsVariable &= ~(1 << myIndex);

要检查位,您可以使用:

if (bitsVariable & (1 << myIndex)) {
    //Bit is set
} else {
    //Bit is not set
}
相关问题