简体   繁体   English

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

[英]Is it possible to define a bit array of custom size

Is it possible to define a bit array of for example 60 bits (It's not divisible by 8)?是否可以定义一个位数组,例如 60 位(它不能被 8 整除)?

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

All I have found defines bit arrays like我发现的所有定义位数组,如

 bit_array = malloc(sizeof(long))

But this only gives 32bits (depending on architecture)但这仅提供 32 位(取决于架构)

Thanks谢谢

Here's code I wrote to manipulate bits from within an array.这是我编写的用于从数组中操作位的代码。 In my code, I allocated 60 bytes of memory from the stack which gives 480 bits for you to play with.在我的代码中,我从堆栈中分配了 60 字节的内存,其中提供了 480 位供您使用。 Then you can use the setbit function to set any bit from within the 60 bytes to either a zero or one, and use getbit to find a value of a bit.然后您可以使用 setbit 函数将 60 个字节内的任何位设置为零或一,并使用 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;
}

This URL has more fragments of code for bit operations:这个 URL 有更多位操作的代码片段:

How do you set, clear, and toggle a single bit? 您如何设置、清除和切换单个位?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM