Microsoft.Scripting.Math.BigInteger.ToByteArray C# (CSharp) Method

ToByteArray() public method

Return the value of this BigInteger as a little-endian twos-complement byte array, using the fewest number of bytes possible. If the value is zero, return an array of one byte whose element is 0x00.
public ToByteArray ( ) : byte[]
return byte[]
    public byte[] ToByteArray() {
      // We could probably make this more efficient by eliminating one of the passes.
      // The current code does one pass for uint array -> byte array conversion,
      // and then a another pass to remove unneeded bytes at the top of the array.
      if (0 == sign) return new byte[] { 0 };

      uint[] dwords;
      byte highByte;

      if (-1 == sign) {
        dwords = (uint[])this.data.Clone();
        makeTwosComplement(dwords);
        highByte = 0xff;
      } else {
        dwords = this.data;
        highByte = 0x00;
      }

      byte[] bytes = new byte[4 * dwords.Length];
      int curByte = 0;
      uint dword;
      for (int i = 0; i < dwords.Length; i++) {
        dword = dwords[i];
        for (int j = 0; j < 4; j++) {
          bytes[curByte++] = (byte)(dword & 0xff);
          dword >>= 8;
        }
      }

      // find highest significant byte
      int msb;
      for (msb = bytes.Length - 1; msb > 0; msb--) {
        if (bytes[msb] != highByte) break;
      }
      // ensure high bit is 0 if positive, 1 if negative
      bool needExtraByte = (bytes[msb] & 0x80) != (highByte & 0x80);

      byte[] trimmedBytes = new byte[msb + 1 + (needExtraByte ? 1 : 0)];
      Array.Copy(bytes, trimmedBytes, msb + 1);

      if (needExtraByte) trimmedBytes[trimmedBytes.Length - 1] = highByte;

      return trimmedBytes;
    }

Usage Example

Example #1
0
 private BigInteger/*!*/ CastToUnsignedBigInteger(BigInteger/*!*/ value) {
     return MakeBigIntegerFromByteArray(value.ToByteArray());
 }
All Usage Examples Of Microsoft.Scripting.Math.BigInteger::ToByteArray