【问题标题】:How to make an array of bits? [duplicate]如何制作一个位数组? [复制]
【发布时间】:2023-03-20 13:11:01
【问题描述】:

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

我试过了

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

但这不会编译,我不认为这是方式

【问题讨论】:

    标签: c bit bit-fields


    【解决方案1】:

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

    要设置位,您可以使用:

    bitsVariable |= 1 << myindex;
    

    要清除位,您可以使用:

    bitsVariable &= ~(1 << myIndex);
    

    要检查位,您可以使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2021-04-10
      • 2013-05-28
      • 1970-01-01
      • 2017-01-01
      • 2013-08-30
      相关资源
      最近更新 更多