是否可以定义一个例如 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 有更多位操作的代码片段:
关于c - 是否可以定义自定义大小的位数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982302/