2013-08-27 22 views
1

鑑於我分配內存是這樣的:在平坦的位域實現中獲取所需位的字節地址?

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); 
    ... 

現在我想要得到的字節對於一個給定的x,y偏移,B:

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

例如,如果我說Create(3, 3, 3)然後DoSomething(0, 1, 1)我會計算字節偏移量爲0.如果我說DoSomething(0, 2, 2)這將是第九位,所以我會計算偏移量爲1.

一旦我有字節我可以執行操作 我需要。

回答

1

首先,我認爲你得到了運算符的優先順序錯誤。如果你做的字節數計算爲

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

那麼它將被解析爲

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

我。即你總是會分配0或1個字節。我想你的意思是

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

改爲。或者只是做平常圍捕招:

numBytes = (numBits + 7)/8; 

現在是的,我們可以自己動手完成的數學,但你爲什麼不乾脆用一個指針到數組,並留下硬數學編譯器?

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

然後是微不足道的獲取地址:

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