gpt4 book ai didi

c# - BigInteger.ToString ("x") 没有正确打印负十六进制数

转载 作者:行者123 更新时间:2023-11-30 13:47:48 29 4
gpt4 key购买 nike

我需要将 BigInteger 打印为负数,但是 ToString("X") 的 Hex 重载不正确。

        BigInteger be1 = new BigInteger();
be1 = 0x7e;
Console.WriteLine(be1.ToString()); // 126
Console.WriteLine(be1.ToString("X")); // 7E
Console.WriteLine(be1.ToString("x")); // 7e
Console.WriteLine();
be1 = BigInteger.Negate(be1);
Console.WriteLine(be1.ToString()); // -126 OK
Console.WriteLine(be1.ToString("X")); // 82 WRONG
Console.WriteLine(be1.ToString("x")); // 82 WRONG

我做错了什么,我该如何解决?

(我这样做是值得的,所以我可以 match the hex output here, illustrated as an C++ array )

最佳答案

ToString 打印一个十六进制整数,就像它是无符号的一样。要将其打印为带有符号的十六进制,请取反值并在其前面加上符号。

BigInteger v = new BigInteger(-10);
string str = "-" + (-v).ToString("X"); // "-0A"

作为扩展方法,它可以像这样工作:

class Program
{
static void Main(string[] args)
{
BigInteger v = new BigInteger(-10);
Console.WriteLine(v.ToSignedHexString()); // Prints: "-0A"
Console.ReadLine();
}
}

public static class BigIntegerExtensions
{
public static string ToSignedHexString(this BigInteger value)
{
if (value.Sign == -1)
return "-" + (-value).ToString("X");
else
return value.ToString("X");
}
}

关于c# - BigInteger.ToString ("x") 没有正确打印负十六进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15201965/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com