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 ?

8
  • @OliCharlesworth yes 010 is decimal. Commented Jun 3, 2014 at 22:04
  • 3
    @Amir No, it's octal. Commented Jun 3, 2014 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 ? Commented Jun 3, 2014 at 22:07
  • Please post some C source code Commented Jun 3, 2014 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. Commented Jun 3, 2014 at 22:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Binary literals in C?
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: stackoverflow.com/a/2612556/395760 -- whether it should be used is another question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.