C 如何将位掩码到字符数组中

标签 c mask bitmask

我有一个 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);

相关问题: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;
}

关于C 如何将位掩码到字符数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10971388/

相关文章:

c - 使用结构 struct { a[0] } 测试;

c - C语言循环6位

Vb.net 图像蒙版使边缘平滑

c - 如何同时应用多个过滤器?

c - libevent API : understanding the pointer parameters or return values

C pthreads 和信号

mask - SnapSVG : Remove mask from an element (unmask)

php - 为什么我应该在 PHP 中使用按位/位掩码?

c - 获取位掩码以交付给所有设备的快速方法

c - 如何用整数中的另一组半字节替换给定的半字节