簡體   English   中英

C如何將位掩碼為char數組

[英]C how to mask bits into char array

我有一個char [16]數組,我從用戶那里獲得輸入:輸入例如-15,21,23,-1

我需要為位置15,21和23將位值設置為“1”.- -1將完成程序。

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

這是我的計划

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”。

用它來設置正確的位:

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

相關問題: 如何設置,清除和切換一個位?

完整代碼示例:

#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;
}

沒有為char定義位字段(如果你使用char使用unsigned ..),請使用unsigned int。 或C99 布爾類型。 https://stackoverflow.com/a/3971334/1419494

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM