-1

I have this code that i am trying to use to convert string of binary to decimal value. However, i am getting the following error:

Value was either too large or too small for a UInt64.

string a = "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101";
ulong value = Convert.ToUInt64(a, 2);
Console.WriteLine(value);

I have tried every possible solution available on the internet, but i'm still not getting the proper solution.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
HarrY
  • 607
  • 4
  • 14
  • 2
    Your number has 95 bits (string is 95 characters long). Of course it is not going to fit into a `UInt64`. – Sweeper Jan 14 '23 at 08:36
  • See also: https://stackoverflow.com/questions/56333862/faster-way-to-convert-large-binary-string-to-biginteger – Sweeper Jan 14 '23 at 08:39

1 Answers1

2

That string is 96 characters. So it represents 96 bits. You are trying to fit that into a UInt64 that, not surprisingly, can hold 64 bits only.

You can use a BigInteger for arbitrary large numbers.

https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?view=net-7.0

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • How to convert BigInteger (binary in my case )to decimal ? – HarrY Jan 14 '23 at 08:52
  • @HarrY define "to decimal" in that sentence. What specific type are you trying to convert it to? What value do you expect? A decimal string should be fine via ToString(), however `double` and `decimal` lack the fidelity to correctly store this number - they just don't have enough bits. There is not currently a `Float128` in the main system libraries, although some seem to exist in 3rd party libs – Marc Gravell Jan 14 '23 at 09:55
  • 1
    @HarrY note that there is now an `Int128` type which would be a lot more efficient than `BigInteger` – Marc Gravell Jan 14 '23 at 09:59
  • @MarcGravell By `decimal` i mean, i want to convert this binary to a number. For Ex: Binary: 11 is 3 in decimal. – HarrY Jan 14 '23 at 11:29
  • @HarrY then: `ToString()` should work, no? (on either `BigInteger` or `Int128`) – Marc Gravell Jan 14 '23 at 15:36
  • @MarcGravell No Marc, `ToString()` did not work. – HarrY Jan 14 '23 at 17:07
  • @HarrY "did not work" how? What did it output? Did you try `ToString("D")`? See also: https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger.tostring?view=net-7.0#system-numerics-biginteger-tostring(system-string) – Marc Gravell Jan 14 '23 at 20:04