dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.96k stars 4.65k forks source link

Add standard numeric format for octal integers #98618

Open colejohnson66 opened 6 months ago

colejohnson66 commented 6 months ago

Similar to x and b for hexadecimal and binary (respectively), o should be provided to format "integral types" as octal.

ghost commented 6 months ago

Tagging subscribers to this area: @dotnet/area-system-numerics See info in area-owners.md if you want to be subscribed.

Issue Details
Similar to `x` and `b` for hexadecimal and binary (respectively), `o` should be provided to format "integral types" as octal.
Author: colejohnson66
Assignees: -
Labels: `area-System.Numerics`, `untriaged`
Milestone: -
huoyaoyuan commented 6 months ago

I don't think octal integers is widely used as binary/hexadecimal.

skyoxZ commented 6 months ago

Convert.ToString(value, 8) can do that. https://learn.microsoft.com/dotnet/api/system.convert.tostring?view=net-8.0#system-convert-tostring(system-int32-system-int32)

colejohnson66 commented 6 months ago

Octal integers are indeed less common than hexadecimal or even binary, but they're still valid numbers, and I think C# should provide more support for them. In addition, while Convert.ToString would work, it incurs an unnecessary allocation if I'm trying to write to a span or an ISH. It's my understanding anyway that the Convert class is "soft-deprecated".

Ultimately, I'd like to be able to work with spans:

int value = ...;
bool ok = value.TryFormat(buffer, out int written, "o", CultureInfo.InvariantCulture);
tannergooding commented 6 months ago

We can't add support for all number bases. Even for binary we only just added the support and that's after the language having had binary literals for several years.

I think we need more information showing that having dedicated octal support is worthwhile, including what spaces (outside of Unix file permissions, for example) that it is needed.

As it stands, the usage scenarios are getting sparse enough that it seems like something which should either be its own general purpose API that works with any number base and not allocating a dedicated format specifier for it.

colejohnson66 commented 6 months ago

Of course, you can't add support for all bases, but octal isn't some "random" number base. I'd wager it's the most common "unsupported" number base in programming.

I'd also be fine with an API that would work with any number base. But the one that does exist (Convert.ToString) throws if the base isn't 2, 8, 10, or 16, and doesn't support CultureInfo or spans.

There's clearly a gap in the API. But you do have a valid point about usage being relatively uncommon.