问题描述
当前方向:
以unsigned char开头,在我的系统上使用sizeof是1字节.范围是0-255.如果length是我需要的位数,那么elements是我数组中需要的元素数(字节).
Start with and unsigned char which is 1 Byte on my system using sizeof. Range is 0-255.If length is the number of bits I need then elements is the number of elements (bytes) I need in my array.
constant unsigned int elements = length/8 + (length % y > 0 ? 1 : 0);
unsigned char bit_arr[elements];
现在,我添加了诸如设置,取消设置和测试之类的基本功能.其中j是每字节索引的位数,i是字节索引,h =位索引.我们有i = h/8和j = i%8.
Now I add basic functionality such as set, unset, and test. Where j is the bit per byte index, i is the byte index and h = bit index. We have i = h / 8 and j = i % 8.
伪代码:
bit_arr[i] |= (1 << j); // Set
bit_arr[i] &= ~(1 << j); // Unset
if( bit_arr[i] & (1 << j) ) // Test
推荐答案
看起来您对需要完成的工作非常了解.尽管可以使用1 << j
代替pow(2, j)
.您还需要更改您的test
代码.您不希望测试对数组进行分配.
Looks like you have a very good idea of what needs to be done. Though instead of pow(2, j)
, use 1 << j
. You also need to change your test
code. You don't want the test to do an assignment to the array.
这篇关于如何实现位数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!