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;
}
CodePudding user response:
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;
CodePudding user response:
The problem of the confusion is that you think that this integer constant 11100000 represents a binary literal. That is 1 and 0 are bit values.
However if you will execute this statement
printf( "11100000 = %x\n", 11100000 );
you will see that the hexadecimal representation of the constant is a95f60
11100000 = a95f60
So in this statement
c = c | 11100000;
the less significant byte that is equal to 0x60 (or in decimal 96) is assigned to the variable c.
It is not the same if to write
c = c | 111;
c <<= 5;
Moreover pay attention to that this expression statement
c << 5;
does not have an effect. It seems you mean
c <<= 5;
that is equivalent to the multiplication of the decimal value 111 by 32 and again assigning the less significant byte to the variable c.
If you will execute this statement
printf( "111 << 5 = %d\n", 111 << 5 );
then you will see that the result is
111 << 5 = 3552
As it is seen 3552 is not the same as 11100000.
So the output of this statement
c = 111 << 5;
printf( "%d\n", c);
is decimal 224.
Opposite to C in C there are no integer binary constants.
In C there are binary literals and you could obtain the expected result running this program
#include <cstdio.h>
int main()
{
unsigned char c = 0;
c = c | 0b11'100'000;
printf( "%o\t", c );
c = 0b111;
c <<= 5;
printf( "%o\n", c );
}
The program output is
340 340
