转换BigInteger
为十进制,十六进制,二进制,八进制字符串:
让我们从一个
BigInteger值开始:
BigInteger bigint = BigInteger.Parse("123456789012345678901234567890");基地10和基地16
内置的base 10(十进制)和base 16(十六进制)覆盖很容易:
// Convert to base 10 (decimal):string base10 = bigint.ToString();// Convert to base 16 (hexadecimal):string base16 = bigint.ToString("X");前导零(BigInteger正值与负值)
请注意,
ToString("X")当的值为BigInteger正时,确保十六进制字符串的前导零。这与
ToString("X")从禁止前导零的其他值类型转换时的通常行为不同。例:
var positiveBigInt = new BigInteger(128);var negativeBigInt = new BigInteger(-128);Console.WriteLine(positiveBigInt.ToString("X"));Console.WriteLine(negativeBigInt.ToString("X"));结果:
08080
此行为有一个目的,因为前导零表示该
BigInteger值为正值-本质上,前导零提供了正负号。这是必要的(与其他值类型转换相反),因为a
BigInteger没有固定的大小;因此,没有指定的符号位。前导零标识一个正值,而不是负数。这允许“往返”
BigInteger值从穿出,再从穿通
ToString()回去
Parse()。MSDN 上的BigInteger
Structure页面上讨论了此行为。
扩展方法:BigInteger到Binary,Hex和Octal
这是一个包含扩展方法的类,用于将
BigInteger实例转换为二进制,十六进制和八进制字符串:
using System;using System.Numerics;using System.Text;/// <summary>/// Extension methods to convert <see cref="System.Numerics.BigInteger"/>/// instances to hexadecimal, octal, and binary strings./// </summary>public static class BigIntegerExtensions{ /// <summary> /// Converts a <see cref="BigInteger"/> to a binary string. /// </summary> /// <param name="bigint">A <see cref="BigInteger"/>.</param> /// <returns> /// A <see cref="System.String"/> containing a binary /// representation of the supplied <see cref="BigInteger"/>. /// </returns> 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' && bigint.Sign == 1) { base2.Append('0'); } // Append binary string to StringBuilder. base2.Append(binary); // Convert remaining bytes adding leading zeros. for (idx--; idx >= 0; idx--) { base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0')); } return base2.ToString(); } /// <summary> /// Converts a <see cref="BigInteger"/> to a hexadecimal string. /// </summary> /// <param name="bigint">A <see cref="BigInteger"/>.</param> /// <returns> /// A <see cref="System.String"/> containing a hexadecimal /// representation of the supplied <see cref="BigInteger"/>. /// </returns> public static string ToHexadecimalString(this BigInteger bigint) { return bigint.ToString("X"); } /// <summary> /// Converts a <see cref="BigInteger"/> to a octal string. /// </summary> /// <param name="bigint">A <see cref="BigInteger"/>.</param> /// <returns> /// A <see cref="System.String"/> containing an octal /// representation of the supplied <see cref="BigInteger"/>. /// </returns> public static string ToOctalString(this BigInteger bigint) { var bytes = bigint.ToByteArray(); var idx = bytes.Length - 1; // Create a StringBuilder having appropriate capacity. var base8 = new StringBuilder(((bytes.Length / 3) + 1) * 8); // Calculate how many bytes are extra when byte array is split // into three-byte (24-bit) chunks. var extra = bytes.Length % 3; // If no bytes are extra, use three bytes for first chunk. if (extra == 0) { extra = 3; } // Convert first chunk (24-bits) to integer value. int int24 = 0; for (; extra != 0; extra--) { int24 <<= 8; int24 += bytes[idx--]; } // Convert 24-bit integer to octal without adding leading zeros. var octal = Convert.ToString(int24, 8); // Ensure leading zero exists if value is positive. if (octal[0] != '0' && bigint.Sign == 1) { base8.Append('0'); } // Append first converted chunk to StringBuilder. base8.Append(octal); // Convert remaining 24-bit chunks, adding leading zeros. for (; idx >= 0; idx -= 3) { int24 = (bytes[idx] << 16) + (bytes[idx - 1] << 8) + bytes[idx - 2]; base8.Append(Convert.ToString(int24, 8).PadLeft(8, '0')); } return base8.ToString(); }}乍一看,这些方法似乎比必要的更为复杂。实际上,确实增加了一些额外的复杂度,以确保转换后的字符串中存在正确的前导零。
让我们检查每种扩展方法,以了解它们如何工作:
BigInteger.ToBinaryString()
以下是使用此扩展方法将a转换
BigInteger为二进制字符串的方法:
// Convert BigInteger to binary string.bigint.ToBinaryString();
这些扩展方法中每种方法的基本核心都是该
BigInteger.ToByteArray()方法。此方法将a转换
BigInteger为字节数组,这是我们如何获取
BigInteger值的二进制表示形式的方法:
var bytes = bigint.ToByteArray();
不过请注意,返回的字节数组是按小端顺序排列的,因此第一个数组元素是的最低有效字节(LSB)
BigInteger。由于使用a
StringBuilder来构建输出字符串(以最高有效位(MSB)开头), 因此必须对字节数组进行反向迭代, 以便首先转换最高有效字节。
因此,将索引指针设置为字节数组中的最高有效数字(最后一个元素):
var idx = bytes.Length - 1;
要捕获转换后的字节,将
StringBuilder创建一个:
var base2 = new StringBuilder(bytes.Length * 8);
该
StringBuilder构造函数采用了容量
StringBuilder。所需的容量
StringBuilder是通过将要转换的字节数乘以8(每个转换的字节产生8个二进制数字)来计算的。
然后将第一个字节转换为二进制字符串:
var binary = Convert.ToString(bytes[idx], 2);
此时,如果
BigIntegera为正值,则必须确保存在前导零(请参见上面的讨论)。如果第一个转换的数字不是零,并且
bigint是正数,则将a
'0'附加到
StringBuilder:
// Ensure leading zero exists if value is positive.if (binary[0] != '0' && bigint.Sign == 1){ base2.Append('0');}接下来,将转换后的字节附加到
StringBuilder:
base2.Append(binary);
要转换剩余的字节,循环以相反的顺序迭代字节数组的其余部分:
for (idx--; idx >= 0; idx--){ base16.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0'));}请注意,根据需要,每个转换的字节在左侧用零(‘0’)填充,因此转换后的字符串为八个二进制字符。这是非常重要的。如果没有此填充,十六进制值“
101”将被转换为二进制值“ 11”。前导零确保转换为“ 100000001”。
转换
StringBuilder完所有字节后,将包含完整的二进制字符串,该字符串由扩展方法返回:
return base2.ToString();
BigInteger.ToOctalString
将a转换
BigInteger为八进制(以8为底)字符串比较复杂。问题是八进制数字代表三个位,这不是由所创建的字节数组的每个元素中保存的八个位的偶数倍
BigInteger.ToByteArray()。为了解决此问题,将数组中的三个字节合并为24位块。每个24位块平均转换为八个八进制字符。
第一个24位块需要一些模数学:
var extra = bytes.Length % 3;
此计算确定将整个字节数组拆分为三字节(24位)的块时有多少个“额外”字节。第一次转换为八进制(最高有效数字)将获得“额外”字节,以便所有剩余的转换将各获得三个字节。
如果没有“额外”字节,则第一个块将获得完整的三个字节:
if (extra == 0){ extra = 3;}第一个块被加载到一个称为
int2424位的整数变量中。块的每个字节都被加载。加载其他字节时,会将之前的位
int24左移8位以腾出空间:
int int24 = 0;for (; extra != 0; extra--){ int24 <<= 8; int24 += bytes[idx--];}将24位块转换为八进制可通过以下方式完成:
var octal = Convert.ToString(int24, 8);
同样,如果
BigIntegera为正值,则第一个数字必须为前导零:
// Ensure leading zero exists if value is positive.if (octal[0] != '0' && bigint.Sign == 1){ base8.Append('0');}转换后的第一个块附加到
StringBuilder:
base8.Append(octal);
其余的24位块将在循环中转换:
for (; idx >= 0; idx -= 3){ int24 = (bytes[idx] << 16) + (bytes[idx -1] << 8) + bytes[idx - 2]; base8.Append(Convert.ToString(int24, 8).PadLeft(8, '0'));}像二进制转换一样,每个转换后的八进制字符串都用零左填充,以使“ 7”变为“ 00000007”。这样可以确保零不会从转换后的字符串中间丢失(即,用“
17”代替“ 100000007”)。
转换为基本x?
将a转换
BigInteger为其他数字基可能要复杂得多。只要数字的底数是2的幂(即2、4、8、16),创建的字节数组
BigInteger.ToByteArray()就可以适当地拆分为位块并进行转换。
但是,如果基数不是2的幂,则问题将变得更加复杂,并且需要进行大量的循环和除法运算。由于这种数基转换很少见,因此我在这里仅介绍了流行的计算数基。



