BigInteger.Parse() 对十六进制数给出负数

发布于 2024-09-04 09:08:03 字数 692 浏览 3 评论 0原文

我已经开始使用 .NET 4 System.Numerics.BigInteger Structure 我遇到了问题。

我正在尝试解析一个包含无符号(正数)的十六进制数字的字符串。我得到一个负数。

例如,我执行以下两个断言:

Assert.IsTrue(System.Int64.Parse("8", NumberStyles.HexNumber, CultureInfo.InvariantCulture) > 0, "Int64");
Assert.IsTrue(System.Numerics.BigInteger.Parse("8", NumberStyles.HexNumber, CultureInfo.InvariantCulture) > 0, "BigInteger");

第一个断言成功,第二个断言失败。我实际上在 BigInteger 中得到 -8 而不是 8。

问题似乎是当我的十六进制以 1 位而不是 0 位(8 和 F 之间的数字(包括 8 和 F)开头)开始时。如果我添加前导 0,一切都会完美。

我这样使用是不是很糟糕?这是 BigInteger 中的错误吗?

I've started using .NET 4 System.Numerics.BigInteger Structure and I've encountered a problem.

I'm trying to parse a string that contains a hexadecimal number with no sign (positive). I'm getting a negative number.

For example, I do the following two asserts:

Assert.IsTrue(System.Int64.Parse("8", NumberStyles.HexNumber, CultureInfo.InvariantCulture) > 0, "Int64");
Assert.IsTrue(System.Numerics.BigInteger.Parse("8", NumberStyles.HexNumber, CultureInfo.InvariantCulture) > 0, "BigInteger");

The first assert succeeds, the second assert fails. I actually get -8 instead of 8 in the BigInteger.

The problem seems to be when I'm the hexadecimal starts with 1 bit and not 0 bit (a digit between 8 and F inclusive). If I add a leading 0, everything works perfectly.

Is that a bad usage on my part? Is it a bug in BigInteger?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飞烟轻若梦 2024-09-11 09:08:03

这正是该方法应该做的事情。

MSDN:BigInteger.Parse 方法

“如果值是十六进制字符串,则
解析(字符串,NumberStyles)方法
将值解释为负数
使用二进制补码存储
表示如果它的前两个
十六进制数字大于或
等于0x80。换句话说,
方法解释最高阶
值中第一个字节的位作为
符号位。为了确保
十六进制字符串正确
解释为正数,则
值中的第一个数字必须有一个值
为零。例如,该方法
将 0x80 解释为负值,
但它解释为 0x080 或
0x0080 为正值。”

It's exactly what the method is supposed to do.

MSDN: BigInteger.Parse Method:

"If value is a hexadecimal string, the
Parse(String, NumberStyles) method
interprets value as a negative number
stored by using two's complement
representation if its first two
hexadecimal digits are greater than or
equal to 0x80. In other words, the
method interprets the highest-order
bit of the first byte in value as the
sign bit. To make sure that a
hexadecimal string is correctly
interpreted as a positive number, the
first digit in value must have a value
of zero. For example, the method
interprets 0x80 as a negative value,
but it interprets either 0x080 or
0x0080 as a positive value."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文