title: Convert BigInteger Binary to BigInteger Number?
body: <p>Currently i am using <code>Long</code> integer type. I used the following to convert from/to  binary/number:</p>
  
  <pre><code>Convert.ToInt64(BinaryString, 2); //Convert binary string of base 2 to number
  Convert.ToString(LongNumber, 2); //Convert long number to binary string of base 2
  </code></pre>
  
  <p>Now the numbers i am using have exceeded 64 bit, so is started using BigInteger. I can't seem to find the equivalent of the code above.</p>
  
  <p>How can i convert from a BinaryString that have over 64bits to a BigInteger number and vice versa ?</p>
  
  <p>Update:</p>
  
  <p>The references in the answer contains the answer i want but i am having some trouble in the conversion from Number to Binary.</p>
  
  <p>I have used the following code which is available in the first reference:</p>
  
  <pre><code>    public static string ToBinaryString(this BigInteger bigint)
      {
          var bytes = bigint.ToByteArray();
          var idx = bytes.Length - 1;
  
          // Create a StringBuilder having appropriate capacity.
          var base2 = new StringBuilder(bytes.Length * 8);
  
          // Convert first byte to binary.
          var binary = Convert.ToString(bytes[idx], 2);
  
          // Ensure leading zero exists if value is positive.
          if (binary[0] != '0' &amp;&amp; bigint.Sign == 1)
          {
              base2.Append('0');
          }
  
          // Append binary string to StringBuilder.
          base2.Append(binary);
  
          // Convert remaining bytes adding leading zeros.
          for (idx--; idx &gt;= 0; idx--)
          {
              base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0'));
          }
  
          return base2.ToString();
      }
  </code></pre>
  
  <p>The result i got is wrong:</p>
  
  <pre><code>100001000100000000000100000110000100010000000000000000000000000000000000 ===&gt;  2439583056328331886592
  2439583056328331886592 ===&gt; 0100001000100000000000100000110000100010000000000000000000000000000000000
  </code></pre>
  
  <p>If you put the resulted binary string under each other, you will notice that the conversion is correct and that the problem is that there is a leading zero from the left:</p>
  
  <pre><code>100001000100000000000100000110000100010000000000000000000000000000000000
  0100001000100000000000100000110000100010000000000000000000000000000000000
  </code></pre>
  
  <p>I tried reading the explanation provided in the code and changing it but no luck.</p>
  
  <p>Update 2:</p>
  
  <p>I was able to solve it by changing the following in the code:</p>
  
  <pre><code>        // Ensure leading zero exists if value is positive.
          if (binary[0] != '0' &amp;&amp; bigint.Sign == 1)
          {
              base2.Append('0');
  
              // Append binary string to StringBuilder.
              base2.Append(binary);
          }
  </code></pre>