Mr. E
Mr. E

Reputation: 2120

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)?

 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)

Thanks

Upvotes: 2

Views: 583

Answers (1)

Mike -- No longer here
Mike -- No longer here

Reputation: 2092

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. 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.

#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:

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

Upvotes: 2

Related Questions