Saphire
Saphire

Reputation: 1930

Bitoperation results not as expected

Here is this simple code:

char a = '10';
char b = '6';
printf("%d\n", a | b);
printf("%d\n", a ^ b);
printf("%d\n", a << 2);

and the output is

54
6
192

Now my question is, why these results. I checked it on paper and what I have is

1110 for a | b = 14
1100 for a ^ b = 12
00101000 for a << 2 = 40

So why this different result?

Upvotes: 0

Views: 66

Answers (3)

RahulKT
RahulKT

Reputation: 171

This is because you defined the variables as character(char) but in the notebook you are calculating the result by treating them as Integer(int) If you want the correct answer try this code and check -

int a = 10; 
int b = 6;
printf("%d\n", a | b);
printf("%d\n", a ^ b);
printf("%d\n", a << 2);

Upvotes: 1

haccks
haccks

Reputation: 106012

You solved this on paper for int 10 and 6 not for chars '10' = 49 or 48 (interpretation of multi-character constant is compiler dependent) and '6' = 54.

Upvotes: 2

Paulo Bu
Paulo Bu

Reputation: 29794

You are declaring:

char a = '10';
char b = '6';

In this case b is 00110110 (0x36) because you are declaring a character, not an integer.

I also don't know why char a = '10'; even works because single quotes (') are used to create only single chars literals and you're declaring two there.

The correct way should be:

char a = 10;
char b = 6;
printf("%d\n", a | b);
printf("%d\n", a ^ b);
printf("%d\n", a << 2);

Upvotes: 3

Related Questions