是否可以定义一个自定义大小的位数组

Is it possible to define a bit array of custom size

是否可以定义一个位数组,例如 60 位(不能被 8 整除)?

 bit_array = malloc(/*What should be here?*/)

我找到的所有内容都定义了像

这样的位数组
 bit_array = malloc(sizeof(long))

但这只给出了 32 位(取决于架构)

谢谢

这是我编写的用于操作数组中的位的代码。在我的代码中,我从堆栈中分配了 60 字节的内存,这为您提供了 480 位供您使用。然后你可以使用 setbit 函数将 60 个字节中的任何位设置为零或 1,并使用 getbit 找到位的值。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int getbit(unsigned char *bytes,int bit){
    return ((bytes[(bit/8)] >> (bit % 8)) & 1);
}

void setbit(unsigned char *bytes,int bit,int val){
    if (val==1){
        bytes[(bit/8)] |= (1 << (bit % 8));
    }else{
        bytes[(bit/8)] &= ~(1 << (bit % 8));
    }
}

int main(int argc, char **argv) {
    unsigned char ab[60]; // value must be the ceiling of num of bits/8
    memset(ab,0,60); // clear the whole array before use.

    //A
    setbit(ab,6,1); 
    setbit(ab,0,1); 

    //B
    setbit(ab,14,1);
    setbit(ab,9,1); 

    //C
    setbit(ab,22,1);
    setbit(ab,17,1);
    setbit(ab,16,1);

    //Change to B
    setbit(ab,16,0);

    printf("ab = %s\n",ab);
    printf("bit 17 = %d\n",getbit(ab,17));

    return 0;
}

这个URL有更多的位操作代码片段:

How do you set, clear, and toggle a single bit?