1

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
4
  • 4
    Avoid "pow". Use bit-shifting << and >> operators instead. (1 << i) == 2^i. Commented May 13, 2011 at 23:08
  • I did not know you can use bit shifting to do that. Thank you. Commented May 13, 2011 at 23:14
  • 1
    <pedantry>There's nothing that guarantees a byte == 8 bits. It can differ per platform/CPU. IIRC CHAR_BITS will tell you how many bits are in a char (which is the same as a byte in C, BTW -- it's defined as the smallest individually addressable unit of memory). </pedantry> Commented May 13, 2011 at 23:15
  • 2
    if( bit_arr[i] &= pow(2,j) ) for the test is wrong, just use & not &=. Commented May 13, 2011 at 23:19

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 as j 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.