简体   繁体   中英

Bit masking result inconsistency

I'm tying to learn about bit masking and I have a question about certain results. Here's some example code.

    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.
        }
    }

So if I output the value of val1 I always get a value between 0 and 3. But when I do a comparison without assigning a type to buffer[e] & 0x3 I don't always get the same result. I tried to output buffer[e] & 0x3 to see what it equals but I get an error. So my question is what are the possible values of buffer[e] & 0x3 when it is being used in the second if statement. Thanks.

that"s because of operator precedence

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

so == has priority on &

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

isn't the same thing as

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

but is

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

(and amounts to (1 == buffer[e]) because masking 0 or 1 with 3 has no effect)

what you want is (1 == (buffer[e] & 0x3))

Seems like a problem with operator precedence: http://en.cppreference.com/w/cpp/language/operator_precedence

1 == buffer[e] & 0x3

is equivalent to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM