java中大的负十六进制值转换为long
结果应该是负值,但实际上是正值。
我该如何解决这个问题?
谢谢!!
BigInteger b = new BigInteger("80000000000000004308000000000000", 16);
System.out.println("长值:"+b.longValue());
--> 长值:4830110600354856960
the result should have a negative value, but its positive.
How can I fix this?
Thanks!!
BigInteger b = new BigInteger("80000000000000004308000000000000", 16);
System.out.println("long value: "+b.longValue());
-->
long value: 4830110600354856960
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的字符串表示形式是有符号长整型,但作为无符号字符串呈现给 BigInteger(符号在字符串开头使用“-”表示)。
需要对字符串进行位移或纠正才能从字符串中进行此操作实例化。
我认为最好的答案是将字符串转换为字节数组并使用 BigInteger(byte[] val) 实例化,它将根据二进制补码识别负数或正数。 许多选项 存在用于字符串到字节数组的转换。任你挑选。
...哦,你的数字太大,无法容纳很长的内容,所以这也会成为一个问题;你得到的是最低有效位。
Your string representation is a signed long but is being presented to BigInteger as an unsigned string (sign is denoted by using a "-" at the start of your string).
Bit shifting or correcting your string is needed to make this work from a string instantiation.
I think the best answer is to convert your string to a byte array and use the BigInteger(byte[] val) instantiation which will recognize a negative or positive number based on two's complement. Many options exist for that string to byte array conversion. Take your pick.
... oh, and your number is too large to fit into a long, so that's going to be an issue too; you get the least significant bits.
http:// /download.oracle.com/javase/1,5,0/docs/api/java/math/BigInteger.html#longValue%28%29
请参阅上面的页面以了解为什么它不会为负数。它返回低 64 位,因此最后 64 位必须高于 Long.MAX_VALUE 才能导致负值。
http://download.oracle.com/javase/1,5,0/docs/api/java/math/BigInteger.html#longValue%28%29
See the above page to understand why it won't be negative. It returns the low 64bits, so your last 64 bits must be higher than Long.MAX_VALUE to cause a negative value.
如果您总是有 128 位数字并假设最高位是您的符号,那么您可以使用以下代码行:
注意:仅当位数适合 a 时,
b.longValue()
才适用。长,但对于如此大的数字可能并非如此。If you always have 128-bit numbers and assume the highest bit is your sign then you can use the following lines:
Note:
b.longValue()
will only be appropriate if the number of bits fits into a long which may not be the case for such large numbers.