0

I have two numbers. 5437 in base 8 and 6312817211 in base 256 for example.. How can I convert both of these to a binary representation? I know how to convert the 5437, that is easy, but I want a algorithm that will deal with both as I can not convert the larger number because it wont fit in a int, it will only fit in a BigInteger which I don't think has any built in ways to convert a BigInteger of base 256 to a binary representation (base 2). Any advice or help would be great. I'm out of ideas and my brain is about to explode.

(I'm working in C# btw)

  • 1
    This discusses BigInteger to binary at length in it's first answer http://stackoverflow.com/questions/14048476/biginteger-to-hex-decimal-octal-binary-strings – rmn36 Sep 14 '15 at 20:03
  • 6
    So what characters are used to represent the 256 different digits? Are you sure you're really working with base 256? – juharr Sep 14 '15 at 20:07
  • You will most likely need to write your own converter. Which isn't hard to do, if you know how different bases work. – Arturo Torres Sánchez Sep 14 '15 at 20:08
  • Are you using all the 8-bit ASCII characters with their associated `int` values as the digits? The formula is just the sum of each digits value times 256 to the power of that digits index starting at 0 on the right and increasing to n-1 on the left. – juharr Sep 14 '15 at 20:12

1 Answers1

0

I have no idea how you're representing base256 integers, but if you've managed to convert them to BigInteger, you can use a converter like this.

static string ToBinary(BigInteger val) {
    if (val < 0) throw new ArgumentOutOfRangeException(nameof(val));
    if (val == 0) return "0";

    var bits = new List<char>();
    while (val > 0) {
        bits.Insert(0, ((val & 1) == 1) ? '1' : '0');
        val >>= 1;
    }
    return string.Concat(bits);
}
recursive
  • 83,943
  • 34
  • 151
  • 241