Org.BouncyCastle.Math.BigInteger.ToByteArray C# (CSharp) Method

ToByteArray() private method

private ToByteArray ( bool unsigned ) : byte[]
unsigned bool
return byte[]
		private byte[] ToByteArray(
			bool unsigned)
		{
			if (sign == 0)
				return unsigned ? ZeroEncoding : new byte[1];

			int nBits = (unsigned && sign > 0)
				?	BitLength
				:	BitLength + 1;

			int nBytes = GetByteLength(nBits);
			byte[] bytes = new byte[nBytes];

			int magIndex = magnitude.Length;
			int bytesIndex = bytes.Length;

			if (sign > 0)
			{
				while (magIndex > 1)
				{
					uint mag = (uint) magnitude[--magIndex];
					bytes[--bytesIndex] = (byte) mag;
					bytes[--bytesIndex] = (byte)(mag >> 8);
					bytes[--bytesIndex] = (byte)(mag >> 16);
					bytes[--bytesIndex] = (byte)(mag >> 24);
				}

				uint lastMag = (uint) magnitude[0];
				while (lastMag > byte.MaxValue)
				{
					bytes[--bytesIndex] = (byte) lastMag;
					lastMag >>= 8;
				}

				bytes[--bytesIndex] = (byte) lastMag;
			}
			else // sign < 0
			{
				bool carry = true;

				while (magIndex > 1)
				{
					uint mag = ~((uint) magnitude[--magIndex]);

					if (carry)
					{
						carry = (++mag == uint.MinValue);
					}

					bytes[--bytesIndex] = (byte) mag;
					bytes[--bytesIndex] = (byte)(mag >> 8);
					bytes[--bytesIndex] = (byte)(mag >> 16);
					bytes[--bytesIndex] = (byte)(mag >> 24);
				}

				uint lastMag = (uint) magnitude[0];

				if (carry)
				{
					// Never wraps because magnitude[0] != 0
					--lastMag;
				}

				while (lastMag > byte.MaxValue)
				{
					bytes[--bytesIndex] = (byte) ~lastMag;
					lastMag >>= 8;
				}

				bytes[--bytesIndex] = (byte) ~lastMag;

				if (bytesIndex > 0)
				{
					bytes[--bytesIndex] = byte.MaxValue;
				}
			}

			return bytes;
		}

Same methods

BigInteger::ToByteArray ( ) : byte[]

Usage Example

        public static byte[] IntegerToBytes(
            BigInteger	s,
            int			qLength)
        {
            byte[] bytes = s.ToByteArray();

            if (qLength < bytes.Length)
            {
                byte[] tmp = new byte[qLength];

                Array.Copy(bytes, bytes.Length - tmp.Length, tmp, 0, tmp.Length);

                return tmp;
            }

            if (qLength > bytes.Length)
            {
                byte[] tmp = new byte[qLength];

                Array.Copy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);

                return tmp;
            }

            return bytes;
        }
All Usage Examples Of Org.BouncyCastle.Math.BigInteger::ToByteArray