c++ - 位屏蔽结果不一致

标签 c++ bit-shift

我想了解位掩码,我对某些结果有疑问。这是一些示例代码。

    FILE * pFile;
    long lSize;
    char * buffer;
    size_t result;

    pFile = fopen ( "testFile.jpg" , "rb" );
    if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

    // obtain file size:
    fseek (pFile , 0 , SEEK_END);
    lSize = ftell (pFile);
    rewind (pFile);

    // allocate memory to contain the whole file:
    buffer = (char*) malloc (sizeof(char)*lSize);
    if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

    // copy the file into the buffer:
    result = fread (buffer,1,lSize,pFile);
    if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

    /* the whole file is now loaded in the memory buffer. */

    for (unsigned long long e = 0; e < lSize; e++){
        unsigned short val1 = buffer[e] & 0x3;
        cout << val1 << endl;
        if (1 == val1){

        }
        if (1 == buffer[e] & 0x3){
            //what does buffer[e] & 0x3 equal when I don't set it equal to an unsigned short.
        }
    }

所以如果我输出 val1 的值我总是得到一个介于 0 和 3 之间的值。但是当我进行比较时没有将类型分配给 buffer[e] & 0x3我并不总是得到相同的结果。我试着输出 buffer[e] & 0x3看看它等于什么,但我得到一个错误。所以我的问题是 buffer[e] & 0x3 的可能值是多少?当它在第二个 if 语句中使用时。谢谢。

最佳答案

那是因为运算符优先

7   == !=   For relational = and ≠ respectively
8   &   Bitwise AND 

所以 == 优先于 &

(1 == buffer[e] & 0x3)

不是一回事

(1 == (buffer[e] & 0x3))

但是是

((1 == buffer[e]) & 0x3)

(相当于 (1 == buffer[e]) 因为用 3 屏蔽 0 或 1 没有效果)

你想要的是(1 == (buffer[e] & 0x3))

关于c++ - 位屏蔽结果不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41537729/

相关文章:

C++指针: dereferencing,赋值等

c++ - 移位运算符如何在两个整数中查找不同位数?

c++ - 使用位移位来缩短 2 个字符会导致值很大的奇怪结果

c++ - 根据成员类型可用性选择 C++ 模板特化

c++ - 从文件中读取数字,递增并写回

Java位移操作: error converting int to byte

c - 如何在 C 中反转 LFSR 和移位寄存器?

c - 如何在 C 中评估移位运算符?

c++ - 在 C++ 中激活 u8 文字

c++ - Windows 10 屏幕坐标偏移 7