How to implement a bitset in C?

前端 未结 7 2142
-上瘾入骨i
-上瘾入骨i 2020-11-30 04:42

I have been using the Bitset class in Java and I would like to do something similar in C. I suppose I would have to do it manually as most stuff in C. What would be an effic

7条回答
  •  情歌与酒
    2020-11-30 04:49

    CCAN has a bitset implementation you can use: http://ccan.ozlabs.org/info/jbitset.html

    But if you do end up implementing it yourself (for instance if you don't like the dependencies on that package), you should use an array of ints and use the native size of the computer architecture:

    #define WORD_BITS (8 * sizeof(unsigned int))
    
    unsigned int * bitarray = (int *)calloc(size / 8 + 1, sizeof(unsigned int));
    
    static inline void setIndex(unsigned int * bitarray, size_t idx) {
        bitarray[idx / WORD_BITS] |= (1 << (idx % WORD_BITS));
    }
    

    Don't use a specific size (e.g. with uint64 or uint32), let the computer use what it wants to use and adapt to that using sizeof.

提交回复
热议问题