c - 是否可以定义自定义大小的位数组

标签 c bit-manipulation bit

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

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

我发现的所有内容都定义了位数组,例如

 bit_array = malloc(sizeof(long))

但这仅提供 32 位(取决于架构)

谢谢

最佳答案

这是我编写的用于操作数组中的位的代码。在我的代码中,我从堆栈中分配了 60 字节内存,这为您提供了 480 位供您使用。然后,您可以使用 setbit 函数将 60 字节内的任意位设置为 0 或 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?

关于c - 是否可以定义自定义大小的位数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982302/

相关文章:

c - 不确定我是否理解如何创建位函数

c - 如何使用位操作在 C 中不使用 + 运算符添加两个数字

c - 使用指定初始化程序时是否有可能获得指向 'this' 结构的指针?

c - 如何从 C 数组中删除空值?

c - 是否可以在文件中间停止从文件扫描?

c# - 如何重置ulong中的单个位?

python - 在python中打印二进制然后求反而不补码

c++ - C++中的整数字节交换

带有尾随零的 Java BitSet

c - 从 C 中的文件中读取混合字符和文字数字