[SOLVED] Why is bitwise OR operation not working as expected when an unsigned char is ORed with 11100000?

Issue

I am not able to understand why the operation ‘c | 11100000’ does not seem to work. But I also noticed that ‘c | 10000000’ works as expected.

#include <stdio.h>

int main()
{
    unsigned char c, c1;
    
    c = c & 0;
    c = c | 11100000;
    printf("%o \t", c);
    
    /** prints 140 ***/
    
    
    c = c & 0;
    c = c | 111;
    c << 5;
    printf("%o", c);
    
    /** prints 157 **/

    return 0;
}

Solution

The constant values that you are using are in decimal format, not binary.

C doesn’t support binary constants, but it does support hex constants:

c = c | 0xe0;
...
c = c | 0x7;

Also, this doesn’t do anything:

c << 5;

Presumably, you want:

c = c << 5;

Answered By – dbush

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.