Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR operator in C not working

Tags:

c

I don't understand why the final printf in the code below is not printing 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);
like image 936
Programmer Avatar asked Nov 28 '22 18:11

Programmer


1 Answers

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

This means, 11111111 (which is 255 written in binary) is equal to -1. (As it's represented as a value stored in two's complement)

To get what you expect, you need to declare c as a unsigned char, like so:

unsigned char c = 0;
int j = 255;
c = (c | j);
printf("The value of c is %d", (int)c);
like image 159
Sebastian Paaske Tørholm Avatar answered Dec 01 '22 06:12

Sebastian Paaske Tørholm