2

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

Mr. E
  • 2,070
  • 11
  • 23
  • I don't think so. `malloc` only has a concept of bytes. What happens at the bit level is implementation defined. – PC Luddite Oct 07 '15 at 01:35
  • 2
    C has no such concept of a "bit array". You can allocate bytes. If you want 7 bits, then you'll have to allocate a whole byte and only use part of it. – user253751 Oct 07 '15 at 01:37
  • If you want to use a bit *field*, it has to be done as part of a structure. – Andrew Henle Oct 07 '15 at 01:42
  • And to use only part of it I should use somekind of bitmask? For example in my 60bits array I should malloc 64 bits (long) and do something like myLong &= 0xFFFFFFFFFFFFFFF // It's 60 bits turned on and the other 4 off – Mr. E Oct 07 '15 at 01:46

1 Answers1

2

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?

Community
  • 1
  • 1
Mike -- No longer here
  • 2,064
  • 1
  • 15
  • 37