如何实现位数组? [英] How do I implement a bit array?

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

问题描述

当前方向:

以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.

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

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