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

4
  • I don't think so. malloc only has a concept of bytes. What happens at the bit level is implementation defined. Commented Oct 7, 2015 at 1: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. Commented Oct 7, 2015 at 1:37
  • If you want to use a bit field, it has to be done as part of a structure. Commented Oct 7, 2015 at 1: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 Commented Oct 7, 2015 at 1:46

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, this was really helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.