58

In C language octal number can be written by placing 0 before number e.g.

 int i = 012; // Equals 10 in decimal.

I found the equivalent of hexadecimal in C# by placing 0x before number e.g.

 int i = 0xA; // Equals 10 in decimal.

Now my question is: Is there any equivalent of octal number in C# to represent any value as octal?

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51
Javed Akram
  • 15,024
  • 26
  • 81
  • 118

5 Answers5

59

No, there are no octal number literals in C#.

For strings: Convert.ToInt32("12", 8) returns 10.

ulrichb
  • 19,610
  • 8
  • 73
  • 87
36

No there isn't, the language specification (ECMA-334) is quite specific.

4th edition, page 72

9.4.4.2 Integer literals

Integer literals are used to write values of types int, uint, long, and ulong. Integer literals have two possible forms: decimal and hexadecimal.

No octal form.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
  • 15
    Update: C# 7 and above now also supports _binary_ literals, such as `0b10` for decimal `2`. – mklement0 Oct 22 '18 at 21:59
  • @mklement0 Odd. The current [6th ed. spec](https://www.ecma-international.org/wp-content/uploads/ECMA-334_6th_edition_june_2022.pdf) (section 6.4.5.3 Integer Literals) still makes no mention of that at all. – General Grievance Aug 22 '22 at 17:54
  • 1
    @GeneralGrievance, that is odd indeed, but I don't know what the exact relationship between the _spec_ and Microsoft's _implementation_ of it is. Binary integer literals _are_ described in the C# docs, namely [here](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types). – mklement0 Aug 22 '22 at 18:07
  • 1
    @mklement0 Ah, I just found Microsoft's own 7.0 spec [here](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/readme), and the link to "Integer Literals" does indeed mention binary (still no octal of course). – General Grievance Aug 22 '22 at 18:14
23

No, there are no octal literals in C#.

If necessary, you could pass a string and a base to Convert.ToInt32, but it's obviously nowhere near as nice as a literal:

int i = Convert.ToInt32("12", 8);
LukeH
  • 263,068
  • 57
  • 365
  • 409
9

No, there are no octal numbers in C#.

Use public static int ToInt32(string value, int fromBase);

fromBase
Type: System.Int32
The base of the number in value, which must be 2, 8, 10, or 16.

MSDN

abatishchev
  • 98,240
  • 88
  • 296
  • 433
3

You can't use literals, but you can parse an octal number: Convert.ToInt32("12", 8).

Mike Dour
  • 3,616
  • 2
  • 22
  • 24