How to implement a bitset in C?

前端 未结 7 2151
-上瘾入骨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:57

    You can give my PackedArray code a try with a bitsPerItem of 1.

    It implements a random access container where items are packed at the bit-level. In other words, it acts as if you were able to manipulate a e.g. uint9_t or uint17_t array:

    PackedArray principle:
      . compact storage of <= 32 bits items
      . items are tightly packed into a buffer of uint32_t integers
    
    PackedArray requirements:
      . you must know in advance how many bits are needed to hold a single item
      . you must know in advance how many items you want to store
      . when packing, behavior is undefined if items have more than bitsPerItem bits
    
    PackedArray general in memory representation:
      |-------------------------------------------------- - - -
      |       b0       |       b1       |       b2       |
      |-------------------------------------------------- - - -
      | i0 | i1 | i2 | i3 | i4 | i5 | i6 | i7 | i8 | i9 |
      |-------------------------------------------------- - - -
    
      . items are tightly packed together
      . several items end up inside the same buffer cell, e.g. i0, i1, i2
      . some items span two buffer cells, e.g. i3, i6
    

提交回复
热议问题