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.
Firstly, I think you got the operator precedence wrong. If you do the calculation of the number of bytes as
then it will be parsed as
i. e. you will always end up with 0 or 1 byte being allocated. I think you meant
instead. Or just do the usual round-up trick:
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?
Then it's trivial to obtain an address: