如何实现位数组?
当前方向:
以 unsigned char 开头,在我的系统上使用 sizeof 为 1 字节。范围是 0-255。 如果 length 是我需要的位数,那么 elements 就是我在数组中需要的元素(字节)数。
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。
伪代码:
bit_arr[i] |= (1 << j); // Set
bit_arr[i] &= ~(1 << j); // Unset
if( bit_arr[i] & (1 << j) ) // Test
Current direction:
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];
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.
Psuedo-Code :
bit_arr[i] |= (1 << j); // Set
bit_arr[i] &= ~(1 << j); // Unset
if( bit_arr[i] & (1 << j) ) // Test
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您非常清楚需要做什么。尽管不是
pow(2, j)
,而是使用1 << j。您还需要更改您的
测试
代码。您不希望测试对数组进行赋值。Looks like you have a very good idea of what needs to be done. Though instead of
pow(2, j)
, use1 << j
. You also need to change yourtest
code. You don't want the test to do an assignment to the array.pow()
会给你浮点值,这是你不想要的。完全没有。当您使用 2 的幂时,它可能对您有用,但随着j
变大,它可能会变得很奇怪。你最好使用
1 << j 代替。消除了任何浮动怪异的可能性,而且它的性能可能也会更好。
pow()
will give you floating-point values, which you don't want. At all. It might work for you, as you use powers of two, but it can get weird asj
gets bigger.You'd do a bit better to use
1 << j
instead. Removes any chance of float weirdness, and it probably performs better, too.