KEMBAR78
[API Proposal]: Support binary format specifier 'b' and 'B' (standard numeric format strings) · Issue #83619 · dotnet/runtime · GitHub
Skip to content

[API Proposal]: Support binary format specifier 'b' and 'B' (standard numeric format strings) #83619

@RaphaelTetreault

Description

@RaphaelTetreault

Background and motivation

.NET/C# supports a wide range of standard numeric format specifiers when calling .ToString on an integer value. Binary numeric formatting is currently only available by calling Convert.ToString([integer], base = 2). It would be convenient if int.ToString([format specifier][precision specifier]) would accept the unused character b and B as the format specifier followed by an optional precision specifier to denote the minimum number of binary digits to display.

API Proposal

namespace System.Globalization;

[Flags]
public partial enum NumberStyles
{
    AllowBinarySpecifier = 0x00000400,
    BinaryNumber = AllowLeadingWhite | AllowTrailingWhite | AllowBinarySpecifier,
}

API Usage

The API would be like so:

string byteBinary = ((byte)42).ToString("B");
string intBinary = (42).ToString("b16");

such that:

Console.WriteLine(byteString);
Console.WriteLine(intString);

will output:

101010
0000000000101010

Alternative Designs

Enable all integer types' (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128) ToString function to accept the format specifier b and B with an optional precision specifier in order to output the value's binary representation as a string.

Risks

There should be none as the b and B format specifiers are not currently in use.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Numericshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions