title: What is the .NET System.Numerics.BigInteger Equivalent of Org.BouncyCastle.Math.BigInteger.ToByteArrayUnsigned?
body: <p>I am currently working with the <a href="http://www.bouncycastle.org/csharp/" rel="nofollow noreferrer">.NET port of BouncyCastle</a> and I am having some trouble converting a big integer into a <code>System.Guid</code> using the native .NET <code>BigInteger</code>.</p>
  
  <p>For some context, I am using BouncyCastle in one ("source") application to convert a <code>System.Guid</code> to a <code>Org.BouncyCastle.Math.BigInteger</code>.  This value is then saved as a string in the format <code>3A2B847A960F0E4A8D49BD62DDB6EB38</code>.</p>
  
  <p>Then, in another ("destination") application, I am taking this saved string value of a <code>BigInteger</code> and am trying to convert it back into a <code>System.Guid</code>.</p>
  
  <p>Please note that in the destination application I do not want BouncyCastle as a reference and would like to use core .NET libraries for the conversion.  However, since I am running into problems converting with core .NET classes, I am using BouncyCastle and the following code does exactly what I would like:</p>
  
  <pre><code>var data = "3A2B847A960F0E4A8D49BD62DDB6EB38";
  var integer = new Org.BouncyCastle.Math.BigInteger( data, 16 );
  var bytes = integer.ToByteArrayUnsigned();
  var guid = new Guid( bytes ); // holds expected value: (7A842B3A-0F96-4A0E-8D49-BD62DDB6EB38)
  </code></pre>
  
  <p>As you can see, there is a <code>ToByteArrayUnsigned</code> method on the <code>Org.BouncyCastle.Math.BigInteger</code> that makes this work.  If I use the <code>ToByteArray</code> on the <code>System.Numerics.BigInteger</code> (even when <a href="https://stackoverflow.com/questions/11849509/convert-guid-to-numeric-equivalent">resizing the array as discussed in this question</a>) it does not work and I get a different <code>System.Guid</code> than expected.</p>
  
  <p>So, what is the best way to perform the equivalent to the above operation using native .NET classes?</p>
  
  <h2>Solution</h2>
  
  <p>Thanks to @John-Tasler's suggestion, it turns out this was due to endianess... darn you endianess... will your endiness ever end? :P</p>
  
  <p><code>
      var parsed = System.Numerics.BigInteger.Parse( "3A2B847A960F0E4A8D49BD62DDB6EB38", NumberStyles.HexNumber ).ToByteArray();
      Array.Resize( ref parsed, 16 );
      var guid = new Guid( parsed.Reverse().ToArray() ); // Hoorrrrayyyy!
  </code></p>