Skip to content

BigInteger.ToString always has a leading zero in bin and hex #115618

Open
dotnet/docs
#46473
@SolalPirelli

Description

@SolalPirelli

Description

I expect BigInteger to behave like other integer types when printed, but for bin and hex that's currently not the case.

This can mess with naive algorithms such as trying to find the bits in a given range using Substring, since the string is not always of the same length.

It's also somewhat annoying when debugging objects that print themselves using BigInteger, e.g., I have a "bit vector" class and a quick glance at something starting with 0... makes me go "wait, I expected this value to be negative when interpreted as a signed integer...".

Reproduction Steps

using System;
using System.Numerics;


Console.WriteLine(9.ToString("D1"));
Console.WriteLine(new BigInteger(9).ToString("D1"));

Console.WriteLine(1.ToString("B1"));
Console.WriteLine(new BigInteger(1).ToString("B1"));

Console.WriteLine(15.ToString("X1"));
Console.WriteLine(new BigInteger(15).ToString("X1"));

Run (e.g. on dotnetfiddle) and you get:

9
9
1
01
F
0F

Expected behavior

BigInteger's bin and hex printing should be consistent with both its own decimal printing and standard integer types' bin/hex/dec printing.

Actual behavior

There is always a leading zero, even when the result can fit exactly in the requested number of digits.

Regression?

Yes for bin, no for hex, changing the dotnetfiddle to .NET 8 outputs:

9
9
1
1
F
0F

Known Workarounds

Checking the length and truncating the string when needed

Configuration

.NET 9, x64, Windows 11. I don't have other OSes to try on and I don't know what dotnetfiddle runs on but I assume this isn't arch- or OS-dependent.

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions