Get byte address for required bit in flat implementation of bit field?

141 views Asked by At

Given that I allocate memory like this:

Create(int width, int height, int depth)
{    
    size_t numBits = width * height * depth;
    size_t numBytes = numBits / 8 + numBits % 8 != 0 ? 1 : 0;
    bytes = malloc(numBytes);
    ...

Now I want to get the byte offset for a given x, y, b:

DoSomething(int x, int y, int bit)
{
    Byte* byte = bytes + ... some offset ...

For example, if I said Create(3, 3, 3) and then DoSomething(0, 1, 1) I would calculate the byte offset as 0. If I said DoSomething(0, 2, 2) that would be the ninth bit so I would calculate the offset as 1.

Once I have the Byte I can perform the manipulations that I need.

1

There are 1 answers

0
AudioBubble On

Firstly, I think you got the operator precedence wrong. If you do the calculation of the number of bytes as

numBits / 8 + numBits % 8 != 0 ? 1 : 0

then it will be parsed as

(numBits / 8 + numBits % 8 != 0) ? 1 : 0

i. e. you will always end up with 0 or 1 byte being allocated. I think you meant

numBits / 8 + (numBits % 8 != 0 ? 1 : 0);

instead. Or just do the usual round-up trick:

numBytes = (numBits + 7) / 8;

Now yes, we can do the maths by hand, but why aren't you simply using a pointer-to-array and leave the hard maths to the compiler?

unsigned char (*mat)[height][depth] = malloc((width + 7) / 8 * sizeof(*mat));

Then it's trivial to obtain an address:

unsigned char *ptr = &mat[x / 8][y][z];