Is there a C# function that formats a 64bit "Unsigned" value to its equivalent binary value?

Viewed 6808

To format/display a number to its equivalent binary form (in C#), I have always simply called:

Convert.ToString(myNumber, 2);

Today, I just realized that the .ToString() overload that I have been calling does not support values that are greater than 9223372036854775807. Note the .ToString() overload's signature is: .ToString(long, int). Where "long" is a 64bit signed value which max's out at 9223372036854775807.

To put it another way, using C#, when I run this:

Convert.ToString(9223372036854775808,2);

It's no surprise (due to the signature) that I receive this exception message:

The best overloaded method match for 'System.Convert.ToString(object, System.IFormatProvider)' has some invalid arguments - Argument 2: cannot convert from 'int' to 'System.IFormatProvider'

My question: Is there a .NET function that allows us to convert values greater than 9223372036854775807 to their equivalent binary format?

3 Answers
public static string UInt64ToBinary(UInt64 input)
{
    UInt32 low = (UInt32) (input & 0xFFFFFFFF);
    UInt32 high = (UInt32) (input & 0xFFFFFFFF00000000) >> 32;
    return $"{Convert.ToString(high, 2).PadLeft(32, '0')}{Convert.ToString(low, 2).PadLeft(32, '0')}";
}
Related