Esempio n. 1
0
        public byte[] EncodeInt(BigInteger bigInt)
        {
            byte[] ret = new byte[32];

            for (int i = 0; i < ret.Length; i++)
            {
                if (bigInt.Sign < 0)
                {
                    ret[i] = 0xFF;
                }
                else
                {
                    ret[i] = 0;
                }
            }

            byte[] bytes;

            //It should always be Big Endian.
            if (BitConverter.IsLittleEndian)
            {
                bytes = bigInt.ToByteArray().Reverse().ToArray();
            }
            else
            {
                bytes = bigInt.ToByteArray().ToArray();
            }

            Array.Copy(bytes, 0, ret, 32 - bytes.Length, bytes.Length);

            return ret;
        }
        public byte[] ConvertTo(object value)
        {
            TypeSerializer.CheckArgument<decimal>(value);
            var decimalValue = (decimal)value;
            int[] bits = decimal.GetBits(decimalValue);

            int scale = (bits[3] >> 16) & 31;

            byte[] scaleBytes = BeConverter.GetBytes(scale);

            var bigintBytes = new byte[13]; // 13th byte is for making sure that the number is positive
            Buffer.BlockCopy(bits, 0, bigintBytes, 0, 12);

            var bigInteger = new BigInteger(bigintBytes);
            if (decimalValue < 0)
            {
                bigInteger = -bigInteger;
            }

            bigintBytes = bigInteger.ToByteArray();
            Array.Reverse(bigintBytes);

            var resultBytes = new byte[scaleBytes.Length + bigintBytes.Length];
            Array.Copy(scaleBytes, resultBytes, scaleBytes.Length);
            Array.Copy(bigintBytes, 0, resultBytes, scaleBytes.Length, bigintBytes.Length);
            return resultBytes;
        }
Esempio n. 3
0
 public ScriptBuilder Push(BigInteger number)
 {
     if (number == -1) return Add(ScriptOp.OP_1NEGATE);
     if (number == 0) return Add(ScriptOp.OP_0);
     if (number > 0 && number <= 16) return Add(ScriptOp.OP_1 - 1 + (byte)number);
     return Push(number.ToByteArray());
 }
        public object ConvertFrom(byte[] decimalBuf)
        {
            var bigintBytes = new byte[decimalBuf.Length - 4];
            Array.Copy(decimalBuf, 4, bigintBytes, 0, bigintBytes.Length);
            //Scale representation is an int, but System.Decimal only supports a scale of 1 byte
            var scale = decimalBuf[3];

            Array.Reverse(bigintBytes);
            var bigInteger = new BigInteger(bigintBytes);
            var isNegative = bigInteger < 0;

            bigInteger = BigInteger.Abs(bigInteger);
            bigintBytes = bigInteger.ToByteArray();
            if (bigintBytes.Length > 13 || (bigintBytes.Length == 13 && bigintBytes[12] != 0))
            {
                throw new ArgumentOutOfRangeException(
                    "decimalBuf",
                    "this java.math.BigDecimal is too big to fit into System.Decimal. Think about using other TypeAdapter for java.math.BigDecimal (e.g. J#, IKVM,...)");
            }

            var intArray = new int[3];
            Buffer.BlockCopy(bigintBytes, 0, intArray, 0, Math.Min(12, bigintBytes.Length));

            return new decimal(intArray[0], intArray[1], intArray[2], isNegative, scale);
        }
Esempio n. 5
0
        public static byte[] Encrypt(byte[] input, BigInteger N, BigInteger E)
        {
            int originalsize = input.Length;
            int inputBlockLength = N.ToByteArray().Length - 1;
            int encodedBlockLength = inputBlockLength + 1;
            int blocksCount = input.Length / inputBlockLength;
            if (input.Length % inputBlockLength != 0)
            {
                blocksCount++;
                Array.Resize(ref input, blocksCount * inputBlockLength);
            }
            int headerSize = 4;
            byte[] encodedResult = new byte[blocksCount * encodedBlockLength + headerSize];
            Array.Copy(BitConverter.GetBytes(originalsize), encodedResult, 4);
            for (int i = 0; i < (input.Length / inputBlockLength) + 1; i++)
            {
                byte[] block = new byte[inputBlockLength];
                Array.Copy(input, i + inputBlockLength, block, 0, inputBlockLength);
                BigInteger message = new BigInteger(block);
                byte[] bytes = BigInteger.ModPow(message, E, N).ToByteArray();
                Array.Copy(bytes, 0, encodedResult, headerSize + i * encodedBlockLength, bytes.Length);
            }

            return encodedResult;
        }
Esempio n. 6
0
        public HKeyExchange(int exponent, string modulus, string privateExponent) :
            this()
        {
            var keys = new RSAParameters();
            Exponent = new BigInteger(exponent);
            keys.Exponent = Exponent.ToByteArray();

            Modulus = BigInteger.Parse("0" + modulus, NumberStyles.HexNumber);
            keys.Modulus = Modulus.ToByteArray();
            Array.Reverse(keys.Modulus);

            if (!string.IsNullOrWhiteSpace(privateExponent))
            {
                PrivateExponent = BigInteger.Parse("0" + privateExponent, NumberStyles.HexNumber);
                keys.D = PrivateExponent.ToByteArray();
                Array.Reverse(keys.D);

                GenerateDHPrimes(256);
                GenerateDHKeys(DHPrime, DHGenerator);
            }

            RSA = new RSACryptoServiceProvider();
            RSA.ImportParameters(keys);

            _blockSize = (RSA.KeySize -
                RSA.LegalKeySizes[0].SkipSize) / 8;
        }
Esempio n. 7
0
 public static byte[] EncodeMPBigInteger(BigInteger value)
 {
     byte[] rawEncoding = value.ToByteArray();
     Array.Reverse(rawEncoding);
     byte[] lengthEncoded = EncodeBEWord((uint)rawEncoding.Length);
     return CombineByteArrays(lengthEncoded, rawEncoding);
 }
Esempio n. 8
0
 public static byte[] EncodeInt(BigInteger y)
 {
     byte[] nin = y.ToByteArray();
     var nout = new byte[Math.Max(nin.Length, 32)];
     Array.Copy(nin, nout, nin.Length);
     return nout;
 }
Esempio n. 9
0
 public void BigIntegerConstruction(BigInteger bi)
 {
     var biBytes = new byte[32];
     bi.ToByteArray().CopyTo(biBytes, 0);
     var hash = new Hash256(bi);
     Assert.AreElementsEqual(biBytes, hash.Bytes);
 }
Esempio n. 10
0
        /// <summary>
        /// Creates instance of RSA cryptography algorithm class
        /// </summary>
        /// <param name="p">Prime number P</param>
        /// <param name="q">Prime number Q</param>
        public RSA(BigInteger p, BigInteger q)
        {
            P = p;
            Q = q;

            KeySize = (p > q) ? (p.ToByteArray().Length * 8) : (q.ToByteArray().Length * 8);
        }
Esempio n. 11
0
        public static byte[] Base58ToByteArray(string base58)
        {
            BigInteger bi2 = new BigInteger(0);
            string b58 =new string(B58);

            foreach (char c in base58)
            {
                if (b58.IndexOf(c) != -1)
                {
                    bi2 = BigInteger.Multiply(bi2, Big58);
                    bi2 = BigInteger.Add(bi2, b58.IndexOf(c));
                }
                else
                    return null;
            }

            byte[] bb = bi2.ToByteArray();
            if (bb[bb.Length-1]==0)
            {
                byte[] withoutZero = new byte[bb.Length-1];
                Buffer.BlockCopy(bb, 0, withoutZero, 0, bb.Length - 1);
                bb = withoutZero;
            }
            Array.Reverse(bb);
            return bb;
        }
Esempio n. 12
0
 private void encryptFile(object sender, RoutedEventArgs e)
 {
     var bytes = File.ReadAllBytes(filePathOpen.Text);
     var open_key = File.ReadAllLines(SenderPath + @"\open_key.txt");
     var D = new BigInteger(open_key[0].Split(' ').Select(a => byte.Parse(a.ToString(), NumberStyles.HexNumber)).ToArray());
     var N = new BigInteger(open_key[1].Split(' ').Select(a => byte.Parse(a.ToString(), NumberStyles.HexNumber)).ToArray());
     var cryptArr = new BigInteger[(bytes.Length / (N.ToByteArray().Length - 1) + 1)];
     for (int i = 0, k = 0; i < bytes.Length; i = i)
     {
         var data = bytes.Skip(i).Take(N.ToByteArray().Length - 1).ToArray();
         cryptArr[k++] = RSAEx.EnCrypt(new BigInteger(data), D, N);
         i += data.Length;
     }
     File.WriteAllLines(filePathEncrypt.Text, cryptArr.Select(intg => string.Join(" ", intg.ToByteArray().Select(a => a.ToString("X")))));
     MessageBox.Show("Шифрование завершено");
 }
Esempio n. 13
0
        void CalculateV(BigInteger x, bool calcB)
        {
            v = BigInteger.ModPow(gBN, x, BN);
            V = v.ToByteArray();

            if (calcB)
                CalculateB();
        }
Esempio n. 14
0
 private static BigInteger BigRandom(this Random rand, BigInteger max)
 {
     var bytes = max.ToByteArray();
     var maxByte = bytes[bytes.Length - 1];
     rand.NextBytes(bytes);
     bytes[bytes.Length - 1] = (byte)rand.Next(maxByte);
     return new BigInteger(bytes);
 }
 public static BigInteger Next(this RNGCryptoServiceProvider random, BigInteger max)
 {
     var arrSize = max.ToByteArray().Length.NextPowerOfTwo();
     var tempArr = new Byte[arrSize];
     random.GetBytes(tempArr);
     var next = new BigInteger(tempArr) & 0x7fffffff;
     return next % max;
 }
Esempio n. 16
0
        public Coprimes(BigInteger target, BigInteger min, BigInteger max)
        {
            Target = new BigInteger(target.ToByteArray());
            Min = min;
            Max = max;

            counter = Min;
        }
Esempio n. 17
0
        public static BigInteger DoBinaryOperatorMine(BigInteger num1, BigInteger num2, string op)
        {
            List<byte> bytes1 = new List<byte>(num1.ToByteArray());
            List<byte> bytes2 = new List<byte>(num2.ToByteArray());

            switch (op)
            {
                case "bMin":
                    return new BigInteger(Negate(Max(Negate(bytes1), Negate(bytes2))).ToArray());
                case "bMax":
                    return new BigInteger(Max(bytes1, bytes2).ToArray());
                case "b>>":
                    return new BigInteger(ShiftLeft(bytes1, Negate(bytes2)).ToArray());
                case "b<<":
                    return new BigInteger(ShiftLeft(bytes1, bytes2).ToArray());
                case "b^":
                    return new BigInteger(Xor(bytes1, bytes2).ToArray());
                case "b|":
                    return new BigInteger(Or(bytes1, bytes2).ToArray());
                case "b&":
                    return new BigInteger(And(bytes1, bytes2).ToArray());
                case "bLog":
                    return ApproximateBigInteger(Math.Log((double)num1, (double)num2));
                case "bGCD":
                    return new BigInteger(GCD(bytes1, bytes2).ToArray());
                case "bPow":
                    int arg2 = (int)num2;
                    bytes2 = new List<byte>(new BigInteger(arg2).ToByteArray());
                    return new BigInteger(Pow(bytes1, bytes2).ToArray());
                case "bDivRem":
                    BigInteger ret = new BigInteger(Divide(bytes1, bytes2).ToArray());
                    bytes1 = new List<byte>(num1.ToByteArray());
                    bytes2 = new List<byte>(num2.ToByteArray());
                    outParam = new BigInteger(Remainder(bytes1, bytes2).ToArray());
                    return ret;
                case "bRemainder":
                case "b%":
                    return new BigInteger(Remainder(bytes1, bytes2).ToArray());
                case "bDivide":
                case "b/":
                    return new BigInteger(Divide(bytes1, bytes2).ToArray());
                case "bMultiply":
                case "b*":
                    return new BigInteger(Multiply(bytes1, bytes2).ToArray());
                case "bSubtract":
                case "b-":
                    bytes2 = Negate(bytes2);
                    goto case "bAdd";
                case "bAdd":
                case "b+":
                    return new BigInteger(Add(bytes1, bytes2).ToArray());
                default:
                    Console.WriteLine("Invalid operation found: {0}", op);
                    break;
            }
            return new BigInteger();
        }
Esempio n. 18
0
        /// <summary>
        /// Equivalent of "return random x in [min;max]"
        /// </summary>
        public BigInteger GetBigInteger(BigInteger min, BigInteger max)
        {
            byte[] bytes = max.ToByteArray();
            _rng.GetBytes(bytes);
            var rand = new BigInteger(bytes);
            if (rand < 0) rand = -rand;

            return (rand % (max - min)) + min;
        }
 /// <summary>
 /// Generates a random odd BigInteger greater than the specified minimum.
 /// </summary>
 /// <param name="min">The minimum.</param>
 /// <param name="token">A cancellation token. The method will bail out ASAP if a cancellation is requested.</param>
 public BigInteger GetRandomOddBigIntegerGreaterThan(BigInteger min, CancellationToken token)
 {
     //we actually compute the highest possible value for the number of bits in min,
     //and then call RandomOddBigIntegerInRange with this value as the maximum.
     byte[] bytes = min.ToByteArray();
     var nBitsMax = bytes.Length * 8;
     BigInteger max = BigInteger.Pow(2, nBitsMax);
     return GetRandomBigIntegerInRange(min, max, token, true);
 }
Esempio n. 20
0
 // Token: 0x06001950 RID: 6480 RVA: 0x0007806C File Offset: 0x0007626C
 public override void WriteValue(object value)
 {
     if (value is System.Numerics.BigInteger)
     {
         System.Numerics.BigInteger bigInteger = (System.Numerics.BigInteger)value;
         base.SetWriteState(JsonToken.Integer, null);
         this.AddToken(new BsonBinary(bigInteger.ToByteArray(), BsonBinaryType.Binary));
         return;
     }
     base.WriteValue(value);
 }
Esempio n. 21
0
        private static uint256 ToUInt256(this System.Numerics.BigInteger input)
        {
            if (input.Sign < 1)
            {
                throw new ArgumentException(nameof(input), "input should not be negative");
            }

            var arr = input.ToByteArray();
            int len = arr.Length;

            if (arr[^ 1] == 0)
Esempio n. 22
0
File: Misc.cs Progetto: sorrge/LSAG
        public static BigInteger GenerateInteger(this RandomNumberGenerator rng, BigInteger max, int securityParameter = 64)
        {
            // The simple modular method from the NIST SP800-90A recommendation
              if (securityParameter < 64)
            throw new SecurityException("Given security parameter, " + securityParameter + ", is too low.");

              var bytesToRepresent = max.ToByteArray().Length;
              var bytes = new byte[bytesToRepresent + securityParameter / 8 + 1];
              rng.GetBytes(bytes);
              bytes[bytes.Length - 1] = 0;
              return BigInteger.Remainder(new BigInteger(bytes), max);
        }
        /**
         * Converts a multi-precision integer (MPI) s into an
         * octet sequence of length k.
         * 
         * @param s the multi-precision integer to convert.
         * @param k the length of the output.
         * @return the result of the transform.
         * @exception ArgumentException if the length in octets of meaningful
         *              bytes of s is greater than k.
         */
        public static byte[] I2OSP(BigInteger s, int k)
        {
            byte[] result = s.ToByteArray().Reverse().ToArray();
            if (result.Length < k)
            {
                byte[] newResult = new byte[k];
                Array.Copy(result, 0, newResult, k - result.Length, result.Length);
                result = newResult.Reverse().ToArray();
            }

            return result;
        }
Esempio n. 24
0
        public byte[] EncodeInt(BigInteger bigInt)
        {
            var ret = new byte[32];

            for (var i = 0; i < ret.Length; i++)
                if (bigInt.Sign < 0)
                    ret[i] = 0xFF;
                else
                    ret[i] = 0;

            byte[] bytes;

            //It should always be Big Endian.
            if (BitConverter.IsLittleEndian)
                bytes = bigInt.ToByteArray().Reverse().ToArray();
            else
                bytes = bigInt.ToByteArray().ToArray();

            Array.Copy(bytes, 0, ret, 32 - bytes.Length, bytes.Length);

            return ret;
        }
Esempio n. 25
0
    static BigInteger BigRandom(BigInteger n)
    {
        var array = n.ToByteArray();
        int last;

        byte temp;
        while ((temp = array[last = array.Length - 1]) == 0)
            Array.Resize<byte>(ref array, last);
        rnd.NextBytes(array);
        array[last] = (byte)rnd.Next(last == 0 ? 2 : 0, temp);

        return new BigInteger(array);
    }
Esempio n. 26
0
 private BigInteger LosujLiczbeZPrzedzialu(BigInteger wartoscMin, BigInteger wartoscMax)
 {
     var dlugosc = wartoscMax.ToByteArray().Length;
     var bity = new byte[dlugosc];
     BigInteger liczba;
     do
     {
         rng.GetBytes(bity);
         liczba = BigInteger.Abs(new BigInteger(bity));
     }
     while (liczba < wartoscMin || liczba >= wartoscMax);
     return liczba;
 }
Esempio n. 27
0
        public static BigInteger NextBigInteger(this Random random, BigInteger maxValue)
        {
            if (maxValue < 0)
                throw new ArgumentException("maxValue must be positive or 0");

            if (maxValue == 0)
                return new BigInteger(0);

            byte[] maxValueArray = maxValue.ToByteArray();
            maxValueArray = maxValueArray.Reverse().ToArray();
            RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
            byte[] data = new byte[maxValueArray.Length];
            provider.GetBytes(data);
            BigInteger resInt;

            int byteNumber = 0;
            byte maxValueFirstByte = maxValueArray[byteNumber];
            byte dataFirstByte = data[byteNumber];
            while (true)
            {
                if (maxValueFirstByte > dataFirstByte)
                {
                    data[byteNumber] = dataFirstByte;
                    break;
                }
                if (maxValueFirstByte == dataFirstByte)
                {
                    if (byteNumber + 1 >= maxValueArray.Length)
                    {
                        data[byteNumber] = dataFirstByte;
                        data = data.Reverse().ToArray();
                        resInt = new BigInteger(data);

                        return (--resInt);
                    }

                    data[byteNumber] = dataFirstByte;
                    byteNumber++;
                    maxValueFirstByte = maxValueArray[byteNumber];
                    dataFirstByte = data[byteNumber];
                    continue;
                }
                dataFirstByte >>= 1;
            }

            data = data.Reverse().ToArray();
            resInt = new BigInteger(data);

            return resInt;
        }
Esempio n. 28
0
File: NLS.cs Progetto: Mofsy/jinxbot
        /// <summary>
        /// Creates a new NLS login context.
        /// </summary>
        /// <param name="username">The username to use for authentication.</param>
        /// <param name="password">The password to use for authentication.</param>
        /// <remarks>
        /// This type does not validate the sequence from moving from one message to the next.  Ensure that you
        /// have the correct sequence of calls.
        /// </remarks>
        /// <returns>An NLS context ID.</returns>
        public NLS(string username, string password)
        {
            userName = username;
            userNameAscii = Encoding.ASCII.GetBytes(userName);
            password = password;

            byte[] rand_a = new byte[32];
            s_rand.GetNonZeroBytes(rand_a);
            a = new BigInteger(rand_a);
            a %= s_modulus;

            a = new BigInteger(ReverseArray(a.ToByteArray()));
            A = new BigInteger(ReverseArray(BigInteger.ModPow(s_generator, a, s_modulus).ToByteArray()));
        }
Esempio n. 29
0
File: DH.cs Progetto: gaijenbon/ngit
 //    myKeyAgree=KeyAgreement.getInstance("DiffieHellman");
 /// <exception cref="System.Exception"></exception>
 public virtual byte[] GetE()
 {
     if (e == null)
     {
         DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g);
         myKpairGen.Initialize(dhSkipParamSpec);
         Sharpen.KeyPair myKpair = myKpairGen.GenerateKeyPair();
         myKeyAgree.Init(myKpair.GetPrivate());
         //    BigInteger x=((javax.crypto.interfaces.DHPrivateKey)(myKpair.getPrivate())).getX();
         //byte[] myPubKeyEnc = myKpair.GetPublic().GetEncoded();
         e = ((DHPublicKey)(myKpair.GetPublic())).GetY();
         e_array = e.ToByteArray();
     }
     return e_array;
 }
Esempio n. 30
0
 public static BigInteger NextRand(BigInteger max)
 {
     BigInteger ret = 0;
     var rng = new RNGCryptoServiceProvider();
     byte[] bytes = max.ToByteArray();
     int ile = bytes.Count();
      ile = rand.Next(1, ile);
      bytes = new byte[ile];
     do
     {
         rng.GetBytes(bytes);
         ret = new BigInteger(bytes);
     } while (ret > max || ret<0);
     return ret;
 }
Esempio n. 31
0
        public static BigInteger PositiveOddRandom(BigInteger lowerBound, BigInteger upperBound)
        {
            byte[] bytes = upperBound.ToByteArray();
            BigInteger result;
            var random = new Random(DateTime.Now.Millisecond);
            do
            {
                random.NextBytes(bytes);
                bytes[bytes.Length - 1] &= (byte)0x7F; //force sign bit to positive
                bytes[0] = (byte)(bytes[0] | 1);
                result = new BigInteger(bytes);
            } while (result < lowerBound || result >= upperBound);

            return result;
        }
Esempio n. 32
0
    public static bigint PrivateKey(bigint primeP)
    {
        var buffer = new byte[primeP.ToByteArray().Length];

        var random = new Random();

        random.NextBytes(buffer);
        bigint result;

        while ((result = new bigint(buffer, true)) > primeP)
        {
            random.NextBytes(buffer);
        }

        return(result);
    }
Esempio n. 33
0
        public static string BigIntegerToBase64(BigInteger data, bool asLittleEndian)
        {
            if (data == null || data == 0)
            {
                return null;
            }

            byte[] bytes = data.ToByteArray();

            if (!asLittleEndian)
            {
                Array.Reverse(bytes);
            }

            return Convert.ToBase64String(bytes);
        }
Esempio n. 34
0
    public static string ToBinaryString(this System.Numerics.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' && bigint.Sign == 1)
        {
            base2.Append('0');
        }
        base2.Append(binary);
        for (idx--; idx >= 0; idx--)
        {
            base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0'));
        }
        return(base2.ToString());
    }
Esempio n. 35
0
        private static string FormatBigIntegerToHex(BigInteger value, char format, int digits, NumberFormatInfo info)
        {
            Debug.Assert(format == 'x' || format == 'X');

            // Get the bytes that make up the BigInteger.
            Span <byte> bits = stackalloc byte[64]; // arbitrary limit to switch from stack to heap

            bits = value.TryWriteBytes(bits, out int bytesWritten) ?
                   bits.Slice(0, bytesWritten) :
                   value.ToByteArray();

            Span <char> stackSpace = stackalloc char[128]; // each byte is typically two chars
            var         sb         = new ValueStringBuilder(stackSpace);
            int         cur        = bits.Length - 1;

            if (cur > -1)
            {
                // [FF..F8] drop the high F as the two's complement negative number remains clear
                // [F7..08] retain the high bits as the two's complement number is wrong without it
                // [07..00] drop the high 0 as the two's complement positive number remains clear
                bool clearHighF = false;
                byte head       = bits[cur];

                if (head > 0xF7)
                {
                    head      -= 0xF0;
                    clearHighF = true;
                }

                if (head < 0x08 || clearHighF)
                {
                    // {0xF8-0xFF} print as {8-F}
                    // {0x00-0x07} print as {0-7}
                    sb.Append(head < 10 ?
                              (char)(head + '0') :
                              format == 'X' ? (char)((head & 0xF) - 10 + 'A') : (char)((head & 0xF) - 10 + 'a'));
                    cur--;
                }
            }

            if (cur > -1)
            {
                Span <char> chars     = sb.AppendSpan((cur + 1) * 2);
                int         charsPos  = 0;
                string      hexValues = format == 'x' ? "0123456789abcdef" : "0123456789ABCDEF";
                while (cur > -1)
                {
                    byte b = bits[cur--];
                    chars[charsPos++] = hexValues[b >> 4];
                    chars[charsPos++] = hexValues[b & 0xF];
                }
            }

            if (digits > sb.Length)
            {
                // Insert leading zeros, e.g. user specified "X5" so we create "0ABCD" instead of "ABCD"
                sb.Insert(
                    0,
                    value._sign >= 0 ? '0' : (format == 'x') ? 'f' : 'F',
                    digits - sb.Length);
            }

            return(sb.ToString());
        }