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.

8
  • 1
    My calculator says that 1100010011001000110011₂ equals 3224115₁₀, not 123₁₀. 3224115₁₀ is not too large for Int64. Commented Jan 7, 2012 at 23:50
  • 1
    Have you googled? I found this: cboard.cprogramming.com/csharp-programming/… Commented Jan 7, 2012 at 23:52
  • 1
    How did you get from 123 decimal to 001100010011001000110011 binary? Commented Jan 7, 2012 at 23:52
  • 1
    Smells like homework, who would read that >20 digit number? Commented Jan 7, 2012 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 Commented Jan 8, 2012 at 0:01

1 Answer 1

16

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

OP said it's too big for even int64, so he wants a decimal string.
Yeah, changed it to match his needs.
BigInteger is in System.Numerics which as not referenced by default.
@MikeW: That's why I inserted the location in the sample while you were typing your comment ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.