Question

OK, say I have a boolean array called bits, and an int called cursor

I know I can access individual bits by using bits[cursor], and that I can use bit logic to get larger datatypes from bits, for example:

short result = (bits[cursor] << 3) |
    (bits[cursor+1] << 2) | 
    (bits[cursor+2] << 1) |
     bits[cursor+3];

This is going to result in lines and lines of code when reading larger types like int32 and int64 though.

Is it possible to do a cast of some kind and achieve the same result? I'm not concerned about safety at all in this context (these functions will be wrapped into a class that handles that)

Say I wanted to get an uint64_t out of bits, starting at an arbitrary address specified by cursor, when cursor isn't necessarily a multiple of 64; is this possible by a cast? I thought this

uint64_t result = (uint64_t *)(bits + cursor)[0];

Would work, but it doesn't want to compile.

Sorry I know this is a dumb question, I'm quite inexperienced with pointer math. I'm not looking just for a short solution, I'm also looking for a breakdown of the syntax if anyone would be kind enough.

Thanks!

Was it helpful?

Solution

You could try something like this and cast the result to your target data size.

uint64_t bitsToUint64(bool *bits, unsigned int bitCount)
{
    uint64_t result = 0;
    uint64_t tempBits = 0;
    if(bitCount > 0 && bitCount <= 64)
    {
        for(unsigned int i = 0, j = bitCount - 1; i < bitCount; i++, j--)
        {
            tempBits = (bits[i])?1:0;
            result |= (tempBits << j);
        }
    }
    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top