2013-01-23 87 views
2

編譯下面的代碼時,GCC給出錯誤。評論兩行,而不是其他轉變行工作,但我不知道如果鑄件是必要的和真實的。char *上的按位運算*

錯誤是:無效的操作數爲二進制| (有'char *'和'int')

謝謝。

void bits2byte(int *bits, char *byte) { 
    byte = 0; 
    int i; 
    for (i = 0; i<8; i++) { 
     if (bits[i] == 1) { 
      byte = byte | 0x01; 
      // byte = (char*)((int)byte | 0x01); 
     } 
     if (i<7) { 
      byte = byte << 0x01; 
      // byte = (char*)((int)byte << 0x01); 
     } 
    } 
} 
int main() { 
    int input_bits[] = {1, 1, 0, 1, 0, 0, 1, 1}; 
    char output_byte; 
    bits2byte(input_bits, &output_byte); 
} 

編輯:我明白,這是一個傳遞引用的問題。我試圖修改字節。我希望函數將位轉換爲一個字節。其實我已經用所有的回答者/評論者的方式首先寫了它,但http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr233.htm中的參考例子通過了我的想法。

+1

是您的目標修改字節或字節的地址?你現在正在做後者(包括,在註釋掉的線路中,通過箍環讓編譯器讓你這樣做),我懷疑你想做前... – jimwise

+1

你知道你在做所有關於字節地址的工作都不是自己的字節? –

回答

4

你爲什麼要對指針進行按位操作?這不是一個好主意,這就是爲什麼你會收到編譯器錯誤。

您需要取消引用與*指針得到一個值,你可以做這些操作:

*byte |= 1; 

*byte <<= 1; 

注意使用|=<<=運營商做出的代碼更簡單,這在通過指針操作時更加有用,因爲「目標」表達式比直接變量更長。

2

C標準規定這些操作符的操作數應該有標量類型。

C11(n1570),第6.5.14邏輯或操作
每個操作數應具有標量類型。

您可以投到intptr_t(C99/C11)。

#include <stdint.h> 

intptr_t n = (void *)byte; 

無論如何,很難說你在做什麼。你不想對指針指向的值進行這種操作嗎?在這種情況下,你必須解除引用。

*byte = *byte | 0x01; 
1

這就是你正在嘗試做的(我認爲)

void bits2byte(int *bits, char *byte) { 
    //notice ALL the work is with "*byte" not "byte" which is the address of the byte. 
    *byte = 0; 
    for (int i = 0; i < 8; i++) { 
     *byte <<= 1; 
     if (bits[i] == 1) { 
      *byte |= 1; 
     } 
    } 
} 

int main() { 
    int input_bits[] = {1, 1, 0, 1, 0, 0, 1, 1}; 
    char output_byte; //no use to put value here, we'll override it anyway... 
    bits2byte(input_bits, &output_byte); 
}