1

The & operator deals with the binary format of a decimal number. So 10 & 9 = 8 because

1010 (10)
1001 (9)
=====
1000 (8)

This previous example runs fine. But when I try to do 010 & 010 I expect the result to be 10. However I get 8. Can anyone explain to me why this is happening ?

mc110
  • 2,825
  • 5
  • 20
  • 21
CMPS
  • 7,733
  • 4
  • 28
  • 53
  • @OliCharlesworth yes 010 is decimal. – CMPS Jun 03 '14 at 22:04
  • 3
    @Amir No, it's octal. – AntonH Jun 03 '14 at 22:06
  • @AntonH Okay here's where I am confused ... why the first example was considered as decimal and the second as octal ... is it because of the 0 at the beginning ? – CMPS Jun 03 '14 at 22:07
  • Please post some C source code – abligh Jun 03 '14 at 22:09
  • 3
    @Amir `10` is considered **decimal**, because it's default. When it starts with a `0`, it's considered **octal**. `0x` is considered as **hexadecimal**. As has been pointed out to me, there's no C standard for binary, although some compilers (such as GCC) consider `0b` as **binary** representation. – AntonH Jun 03 '14 at 22:09
  • Good info here: http://stackoverflow.com/questions/15114140/writing-binary-number-system-in-c-code – AntonH Jun 03 '14 at 22:11
  • Oh okay, thanks. Can you write an answer to mark solved. – CMPS Jun 03 '14 at 22:12
  • @Amir Put an answer up. – AntonH Jun 03 '14 at 22:14

1 Answers1

2

Because a number that starts with a 0 is considered as being octal, not binary.

10 is considered decimal, because it's default. So the 10 & 9 = 8 test is resolved in decimal.

When it starts with a 0, it's considered octal. So 010 & 010 is resolved in octal, as (in decimal): 8 & 8.

0x is considered as hexadecimal.

And as Oli Charlesworth and delnan pointed out to me, there's no C standard for binary, although some compilers (such as GCC) consider 0b as binary representation.

Interesting info here: Writing binary number system in C code

Community
  • 1
  • 1
AntonH
  • 6,359
  • 2
  • 30
  • 40
  • Binary literals in C? – Oliver Charlesworth Jun 03 '14 at 22:04
  • 1
    `0b010` is, unfortunately, only available in C++11. Or is there an equivalent extension in GNU C or something? Edit: Actually, there is such an extension: http://stackoverflow.com/a/2612556/395760 -- whether it should be used is another question. –  Jun 03 '14 at 22:04