处理大型数字输入和输出十六进制字符串



我需要获取大于 64 位的数字输入,确保仅丢弃剩余的 83 位(如果输入大于 83 位(并将其转换为十六进制字符串。

我发现我可以使用BigInteger(System.Numerics.BigInteger(来接受来自用户的数字输入,但我不确定如何继续此操作。我在下面概述了我的方法:

BigInteger myBigInteger = BigInteger.Parse("123456789012345678912345");
byte[] myByte = myBigInteger.ToByteArray();
if (myByte.Length < 11) // if input is less than 80 bits
{
// Convert Endianness to Big Endian 
// Convert myBigInteger to hex and output
}
// Drop the elements greater than 11
// Convert element 10 to int and & it with 0x7F
// Replace the element in the array with the masked value
// Reverse array to obtain Big Endian
// Convert array into a hex string and output

我不确定我的想法是解决这个问题的正确方法。任何建议将不胜感激。

谢谢。

作弊! :-(

public static readonly BigInteger mask = new BigInteger(new byte[]
{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0x07
});
static void Main(string[] args)
{
BigInteger myBigInteger = BigInteger.Parse("1234567890123456789123450000");
BigInteger bi2 = myBigInteger & mask;
string str = bi2.ToString("X");

使用按位&使用预先计算的掩码截断您的数字!然后使用.ToString("X")以十六进制形式编写它。

请注意,如果您需要正好 83 位,那么它是 10 个块的 8 位加上 3 位......最后 3 位0x07不0x7F!

请注意,您可以:

string str = bi2.ToString("X21");

将数字填充为 21 位(作为可以用 83 位表示的最大十六进制数(

最新更新