-3
int main()
{
    uint32_t n1 = 00000000000000000000000000001000;
    uint32_t n2 = 00000000000000000000000000000100;
    cout << n2; 
}

When I use Visual Studio 2013 (C++), I am getting the result as 64.

Why is this turning to octal number system instead of binary?

Praveen Vinny
  • 2,372
  • 6
  • 32
  • 40
  • Where did you ask the computer to interpret it as binary? Not realising that it would be an octal literal I can understand, but then why would you not expect decimal instead? – Lightness Races in Orbit Nov 06 '16 at 03:06

2 Answers2

3

That's because a number with a leading 0 is considered to be an octal number:

auto num = 04; //Octal number

In C++14 and later, if you want to specify binary numbers, you will have to use the 0b prefix:

uint32_t n2 = 0b00000000000000000000000000000100;
              ^^

If you can't use C++14, you will have to use bit shifts or similar techniques to get the desired result.

For decimal numbers, you will have to get rid of the leading 0s.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
2

Starting a numeric literal with 0 means you want it interpreted as octal, which is what I assume you meant when you used "octonary", a word I haven't seen before and, while it appears to be a real word, you'll probably get some blank stares if you use it :-)

This treatment as octal is as per the standard, C++11 2.14.2 Integer literals /1:

An octal integer literal (base eight) begins with the digit 0 and consists of a sequence of octal digits.

For binary numbers, probably the easiest way to do it is with bit shifting (pre C++14):

uint32_t n1 = 1u << 3;
uint32_t n2 = 1u << 2;

C++14 provides the 0b prefix, akin to the 0x one for hexadecimal numbers but I'm not entirely convinced that's as readable as the other option if you still use a large number of leading zeros:

uint32_t n1 = 0b00000000000000000000000000001000;
uint32_t n2 = 0b00000000000000000000000000000100;

Seasoned coders, of course, can instantly map from binary to hex so would probably just use:

uint32_t n1 = 0x00000008;
uint32_t n2 = 0x00000004;
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953