Gaspa79 Gaspa79 - 1 month ago 25
C# Question

.NET Ulong to binary string representation?

I now want to print on the screen the binary (base 2) representation of a ulong (i.e. something like 0000000000000000000000001, I know that's not enough zeroes)

I just noticed that for some reason there's no Convert.ToString(ulong, base) overload, meaning that I can convert a long into a base2 string representation, but I can't do the same with ulong.

Is there any other .net method to do this? Is there a reason why this method is not there? (the method is there for uint). Will casting it to a long yield the same results?

Thanks a lot =)

Answer

Well, you could write Convert.ToString((long)value, 2);

Casting a ulong to long doesn't change the bit pattern at all.

As I recall, there are no Convert methods to deal with UInt64 or UInt32 because Convert is intended to be CLS Compliant, and public methods that deal with unsigned values aren't CLS Compliant.

See Common Language Specification.

This does not change the bit pattern. Consider:

ulong foo = 0x7FFFFFFFFFFFFFFF;
Console.WriteLine(Convert.ToString((long) foo, 2));

foo = 0x8000000000000000;
Console.WriteLine(Convert.ToString((long)foo, 2));

The output is:

111111111111111111111111111111111111111111111111111111111111111
1000000000000000000000000000000000000000000000000000000000000000

Note that the first line has 63 bits. The high bit is 0. The second line has 64 bits. The high bit is set correctly.