cbit-manipulationbitwise-or

Setting char to all true bits


I am trying to set all bits in a char to true.

char foo = 00000000;
foo |= 11111111;
for (int i = 0; i < 8; i++) { //prints out bitwise
    printf("%d", !!((foo << i) & 0x80));
}

When foo is all 0, I get 11000111. When foo == 00000110, it prints 11001111; What is going wrong here?


Solution

  • The number 11111111 is a decimal constant, not binary. Although you can use octal or hexadecimal constants, there are no binary constants (at least not standard ones).

    If you want a number with all bits set, just apply the bitwise complement operator ~ to 0:

    unsigned char foo = ~0u;