位摆弄很多位在c [英] Bit twiddling a lot of bits in C
问题描述
我想用二进制标志重新present数学集C,其中i位设置为手段项目i是集。这是方便,因为像联盟和十字路口行动是微不足道的实施(|和&安培;)。不过,我想我的一套能够包含超过32个项目。此外,我希望我的code在32位和64位的机器工作。
I would like to use binary flags to represent a mathematical set in C, where "Bit i is set" means "item i is in the Set". This is convenient because operations like "union" and "intersection" are trivial to implement ("|" and "&"). However, I want my set to be able to contain more than 32 items. Furthermore, I want my code to work on both 32 and 64 bit machines.
有没有简单的方法来处理多个单词值得C位的?有没有更好的方式来处理这个任务?
Is there any simple way to manipulate more than one word worth of bits in C? Is there a better way to approach this task?
推荐答案
是的,你只需定义你的32位整数的数组。然后,你操纵数组的特定元素。
Yes, you simply define an array of your 32-bit integers. Then you manipulate a specific element of the array.
假设从0位ID到255包(例如),这将是一个数组:
Given a bit ID from 0 through 255 inclusive (for example), that would be an array:
unsigned int bits[8];
为了找到的这元素进行操作:
In order to find which element to operate on:
unsigned int index = bitId >> 5; // turns 0..255 into 0..31
要获得口罩一个给定的位ID:
To get the masks for a given bit ID:
unsigned int masks[] = {
0x0001, 0x0002, 0x0004, 0x0008,
0x0001, 0x0020, 0x0040, 0x0080,
0x0100, 0x0200, 0x0400, 0x0800,
0x1000, 0x2000, 0x4000, 0x8000
};
unsigned int mask = masks[bitId & 0x1f];
如果您有 uint32_t的
在实现类型可用,这可能是去最安全的方式。否则,有已知的方法使用 unsigned int类型
使用 CHAR_BIT
和的sizeof
在运行时实际弄清楚如何大,使口罩
阵列和什么值应该用于发现数组索引和掩码指数。
If you have the uint32_t
type available in your implementation, that's probably the safest way to go. Otherwise, there are known methods for using unsigned int
using CHAR_BIT
and sizeof
to actually figure out at runtime how big to make the masks
array and what values you should use for discovering the array index and bitmask index.
例如,从我的code库这个片段展示了我是如何做的一个基于字符的位掩码:
For example, this snippet from my code library shows how I did it for a character-based bitmask:
static unsigned char bitmask[CHAR_BIT];
void bitsetInit (void) {
unsigned char mask = 1;
int i = 0;
while (i < CHAR_BIT) {
bitmask[i++] = mask;
mask <<= 1;
}
}
和使用:
bsp->bits[bitnum/CHAR_BIT] &= ~bitmask[bitnum%CHAR_BIT];
bsp->bits[bitnum/CHAR_BIT] |= bitmask[bitnum%CHAR_BIT];
清除和设置分别位。
for clearing and setting bits respectively.
如果你想使用 unsigned int类型
而不是 unsigned char型
您只需将计算该位的数目
If you wanted to use unsigned int
instead of unsigned char
you would simply calculate the number of bits for that:
unsigned int UINT_BIT = CHAR_BIT * sizeof (unsigned int);
和使用它,我已经使用 CHAR_BIT
上方(屏蔽
阵列可以在运行时,如果动态分配需要的话)。
and use it where I've used CHAR_BIT
above (the mask
array can be dynamically allocated at runtime if need be).
这篇关于位摆弄很多位在c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!