Search code examples
c++stringbit-manipulationbitwise-operators

What does this char string related piece of C++ code do?


bool check(const char *text) {
    char c;
    while (c = *text++) {
        if ((c & 0x80) && ((*text) & 0x80)) {
            return true;
        }
    }
    return false;
}

What's 0x80 and the what does the whole mysterious function do?


Solution

  • Rewriting to be less compact:

    while (true)
    {
        char c = *text;
        text += 1;
        if (c == '\0') // at the end of string?
            return false;
        
        int temp1 = c & 0x80;          // test MSB of c
        int temp2 = (*text) & 0x80;    // test MSB of next character
        if (temp1 != 0 && temp2 != 0)  // if both set the return true
            return true;
    }
    

    MSB means Most Significant Bit. Bit7. Zero for plain ascii characters