3

I've got a large text, containing a number as a binary value. e.g '123' would be '001100010011001000110011'. EDIT: should be 1111011

Now I want to convert it to the decimal system, but the number is too large for Int64.

So, what I want: Convert a large binary string to decimal string.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Lennart
  • 345
  • 4
  • 17
  • 1
    My calculator says that 1100010011001000110011₂ equals 3224115₁₀, not 123₁₀. 3224115₁₀ is not too large for Int64. – dtb Jan 07 '12 at 23:50
  • 1
    Have you googled? I found this: http://cboard.cprogramming.com/csharp-programming/123317-convert-binary-decimal-string.html – fury Jan 07 '12 at 23:52
  • 1
    How did you get from 123 decimal to 001100010011001000110011 binary? – Mike W Jan 07 '12 at 23:52
  • 1
    Smells like homework, who would read that >20 digit number? – L.B Jan 07 '12 at 23:53
  • No homework, and i google for that 123 on ascii to bin. Oh, and the numbers represents filecontents. EDIT: 123 should be 1111011 – Lennart Jan 08 '12 at 00:01
  • @MikeW three bytes: 49, 50, 51; as chars: 123 – phoog Jan 08 '12 at 00:02
  • Thanks fury, thats the answer. – Lennart Jan 08 '12 at 00:12
  • If you have trouble fitting the numbers in `long`, you should be careful with `Math.Pow(...)`, since floating point numbers have a limited value range too (and a limited precision, which can quickly lead to wrong and – even worse, since it's not easy to find these bugs – inconsistent results) – Nuffin Jan 08 '12 at 00:53

1 Answers1

14

This'll do the trick:

public string BinToDec(string value)
{
    // BigInteger can be found in the System.Numerics dll
    BigInteger res = 0;

    // I'm totally skipping error handling here
    foreach(char c in value)
    {
        res <<= 1;
        res += c == '1' ? 1 : 0;
    }

    return res.ToString();
}
Nuffin
  • 3,882
  • 18
  • 34