位掩码结果不一致

时间:2017-01-08 20:48:52

标签: 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语句中使用时的可能值是什么。感谢。

2 个答案:

答案 0 :(得分:2)

因为运算符优先级

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

因此==优先于&

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

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

但是

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

(相当于(1 == buffer[e]),因为屏蔽0或1与3无效)

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

答案 1 :(得分:2)

似乎是运算符优先级的问题: http://en.cppreference.com/w/cpp/language/operator_precedence

1 == buffer[e] & 0x3

相当于

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