This project is read-only.

Octal Literals

Topics: C# Language Design
Apr 24, 2014 at 11:25 PM
Whilst I was pleased to see that binary literals are (probably) going to be added to C#, I was disappointed that there was no mention of adding octal literals as well to complete the set.

Although octal isn't used so much these days, it's still occasionally useful and C# is the only C-family language I can think of which doesn't support octal literals. Even VB and F# have them.

I never liked the C/C++/Java syntax of prefixing octal literals with a '0' and you couldn't use that syntax in C# now anyway.

However, you could use a prefix of '0t' or '0o', say. So 64 decimal would either be 0t100 or 0o100.

Does anyone else think it would be worthwhile supporting these?
Apr 25, 2014 at 9:16 AM
What reason would there be for adding that? What are the cases when you think octal is more appropriate than hexadecimal or binary?

I'm asking because I did want to use binary literals in C# on some occasions (mostly when defining flag enums), but I've never once missed octal.
Apr 25, 2014 at 2:24 PM
Thanks for the reply.

In my own case, I'm often given old code (usually written in C), which uses octal literals, to translate into C#.

It can be tedious having to translate these into decimal or hex and I have been known to get them wrong :(

It would be nice if I could just remove the leading zero and replace it with '0t' or whatever.

Admittedly, I could use Convert.ToInt32(string, int) which supports bases of 2, 8, 10, 16 to do the conversion but it's hardly an efficient solution.

I've also answered a number of questions over the years on C# forums from posters bemoaning the lack of octal literals in the language. Here's one for example:

octal numbers - how to use

So, I thought if they are going to add binary literals (something I never expected to see) it wouldn't be much of a stretch to add octal literals at the same time.

OK, it's a very minor feature but for those of us who have to wrestle with old code it would be nice to have :)
Apr 25, 2014 at 3:17 PM
It can be tedious having to translate these into decimal or hex and I have been known to get them wrong :(
You're not using a tool to do it? Seems like that would be far more efficient and safer too.
Apr 25, 2014 at 4:49 PM
Nowadays I use an online converter for those numbers which I can't convert in my head. I copy the octal number into the converter and paste the result back into the code.

It's tedious and somewhat error prone but I can live with it.

I did once write a regular expression based tool which picked out all the octal numbers from the C source code and replaced them with the equivalent decimal numbers. Although it seemed to work OK, using it made me nervous and I found myself double-checking the results which was even slower than converting them one by one!