1

I have a C programming exam a few days later, in the sample that I was given, there is a problem about bitwise operators. Now I know &, |, ^, <<, >> and what they do. But I am kind of confused about this:

int main()
{
int i = 021, j = 0x2A, k,l,m;
k = i | j;
l = i & j;
m = k ^ l;

printf("%d, %d, %d, %d, %d\n",i,j,k,l,m);

return 0;
}

When I test it, the output is: 17 42 59 0 59

But I don't understand how. What is 021 in binary? If I take it as 21, (if I delete the 0 before it, the output changes completely.) Can anyone help please?

P.W
  • 26,289
  • 6
  • 39
  • 76
  • 1
    When you use a leading zero and it is _not_ `0x` (which denotes hex), then `021` is _octal_, which is 17 decimal or `0x11` (hex). It may be more helpful if your `printf` uses `%x` instead of `%d` – Craig Estey Jan 11 '19 at 06:50

1 Answers1

3

What is 021 in binary? If I take it as 21, (if I delete the 0 before it, the output changes completely.)

An integer literal beginning with 0 is an octal number. If you remove the 0, it is a decimal number. So the value of 021 is 2 * 8 + 1 which is 17. The binary representation is 10001.

If 0 is removed, the value of i is 21 and the binary representation is 10101. So the output changes accordingly when used in different operations.

Since you are using the conversion specifier d in your printf statement, all the values printed will be decimal.

P.W
  • 26,289
  • 6
  • 39
  • 76