2012-06-10 25 views
0

我有一個char [16]數組和我得到來自用戶的輸入: 輸入用於示例 - 15,21,23,-1Ç如何屏蔽位轉換成字符數組

我需要設置位15,21和23的位值爲'1'。 -1將完成程序。

每個char [16]數組表示0-127中的值,表示位。 我有問題輸入'1'到15,21和23個單元格中。

這裏是我的程序

int temp; 
char A[16]; 
/*Sets all the cells values to o*/ 
memset(A, 0, 16*sizeof(char)); 
While (int != -1) 
{ 
    scanf("Enter values from the user:%d", val"); 
    div = (temp/8); 
    mod = (temp%8); 
    A[div] |= (mod<<=1); 
} 

它沒有設置電池15,21和23個值的問題「1」。

+7

'<< ='與'<<'不一樣。 –

+3

此外,你還沒有發佈你的實際代碼。請發佈您的實際代碼。 –

+0

它是否將其他單元格設置爲1?還是它沒有設置任何東西? – anatolyg

回答

2

使用此設置右位:

A[div] |= (1<<mod); 

相關問題:How do you set, clear, and toggle a single bit?

完整的代碼示例:

#include <iostream> 

int main() { 
    unsigned char A[16]; 
    memset(A, 0, sizeof(A)); 
    int t; 
    std::cin >> t; 
    while (t != -1) 
    { 
     int div = (t/8); 
     int mod = (t%8); 
     A[div] |= (1<<mod); 
     std::cin >> t; 
    } 
    for(int i = 0; i < 16; ++i) { 
     std::cout << (int)A[i] << " "; 
    } 
    std::cout << std::endl; 
    return 0; 
} 
+0

A [div] | =(1 << mod);返回值16 – judith

+0

它應該返回什麼值? – 2012-06-10 19:32:52

+0

我試圖將該位設置爲1 – judith