OR in C does not work

I do not understand why the final printf in the code below does not print 255.

 char c; c = c & 0; printf("The value of c is %d", (int)c); int j = 255; c = (c | j); printf("The value of c is %d", (int)c); 
+4
source share
4 answers

In most implementations, char signed, so it ranges from -128 to 127 .

This means that 11111111 (which is 255 , written in binary format) is -1 . (Since it is represented as a value stored in two additions )

To get what you expect, you need to declare c as an unsigned char , for example:

 unsigned char c = 0; int j = 255; c = (c | j); printf("The value of c is %d", (int)c); 
+16
source

It probably prints -1. It's because

 c = (c | j); 

will be rated as

 c = (0 | 255) = (0 | 0xFF) = 0xFF 

but since c signed, 0xFF will be -1, not 255, as you expected. If you change c to an unsigned char , it will print 255 as you imagined.

+5
source

Try replacing char c with unsigned char c . Basically, the char type supports values ​​from -128 to 127. Your result is larger than the supported range and overflows.

+2
source

By default, char signed char in C. If you want to print 255 , use unsigned char however I explain the output in the context of signed char so that the concept becomes clear. If you write j=127 , then it will print 127 , since the bit representation is 01111111. But if you write j=128 then it will print -128 because the bit representation 01111111 has increased by 1 to become 10000000. now, if you write j=255 then the bit representation is 11111111. therefore it will print -1 If you write j=256 then it will print 0 because when the bit representation 11111111 increases by 1, it becomes 100000000. But only 1 byte is allocated for the characher variable, so the left the bit itself is not saved, and the bit representation becomes 00000000. Also, if if you write j=257 then this is also an overflow case, and the bit representation will become 00000001 and 1 will be printed.

0
source

Source: https://habr.com/ru/post/1369285/


All Articles