如何实现在C位集? [英] How to implement a bitset in C?

查看:171
本文介绍了如何实现在C位集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用位集合在Java中,我班希望做类似的事情在C.我想我会做手工为C.大部分的东西是什么将是一个有效的方式来实现?

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 efficient way to implement?

byte bitset[]

也许

bool bitset[]

推荐答案

CCAN 有一个bitset实现,你可以使用:的http://ccan.ozlabs.org/info/jbitset.html

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

但是,如果你最终自己实现它(例如,如果你不喜欢在该包的依赖),你应该使用int数组,并使用计算机体系结构的本机尺寸:

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));
}

不要使用特定大小(例如,与UINT64 UINT32或),让计算机使用什么希望利用和适应,使用的sizeof。

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.

这篇关于如何实现在C位集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆