我一直在使用Java中的Bitset类,现在我想在C语言中做类似的事情。我想大多数情况下都需要手动实现。那么,在C语言中实现一个高效的方式是什么呢?
byte bitset[]
也许
bool bitset[]
?
我一直在使用Java中的Bitset类,现在我想在C语言中做类似的事情。我想大多数情况下都需要手动实现。那么,在C语言中实现一个高效的方式是什么呢?
byte bitset[]
也许
bool bitset[]
?
CCAN提供了一个bitset的实现,你可以使用:http://ccan.ozlabs.org/info/jbitset.html
但是如果你最终决定自己实现(例如,如果你不喜欢该程序包上的依赖项),你应该使用int数组并使用计算机架构的本地大小:
#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));
}
不要使用特定的大小(例如uint64或uint32),让计算机使用它想要使用的大小,并使用sizeof进行适应。
sizeof
表示的是字节数而非位数。在某些表达式中需要将其乘以8(或者更一般地,乘以CHAR_BIT
)。 - R.. GitHub STOP HELPING ICEcalloc
的第一个参数不是应该改为 (size + WORD_BITS - 1) / WORD_BITS
吗?因为这是所需的无符号整数数量。 - Björn Lindqvist(idx % WORD_BITS)
可以简化为 (idx & (WORD_BITS - 1))
,但是好的编译器可能会自动进行这种优化。 - Björn Lindqvist<inttypes.h>
中的intfast_t
(或uintfast_t
)而不是普通的int
会更有意义吗?没有保证int
是最有效的类型。在大多数64位系统上,int
只有32位,但使用64位可能更有效率。 - Simon Kissane#include <limits.h> /* for CHAR_BIT */
#define BITMASK(b) (1 << ((b) % CHAR_BIT))
#define BITSLOT(b) ((b) / CHAR_BIT)
#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))
#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)
int i = 0, bits; BITSET(bits, i++)
- Luke Smith嗯,byte bitset[] 看起来有点误导人,不是吗?
在结构体中使用位域,然后您就可以维护这些类型的集合(或根据需要以其他方式使用它们)。
struct packed_struct {
unsigned int b1:1;
unsigned int b2:1;
unsigned int b3:1;
unsigned int b4:1;
/* etc. */
} packed;
bitsPerItem
为 1
的 PackedArray 代码。uint9_t
或 uint17_t
数组一样: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