[英]Large negative hex value conversion to long in java
the result should have a negative value, but its positive. 结果应该是负值,但它是积极的。
How can I fix this? 我怎样才能解决这个问题?
Thanks!! 谢谢!!
BigInteger b = new BigInteger("80000000000000004308000000000000", 16); BigInteger b = new BigInteger(“80000000000000004308000000000000”,16);
System.out.println("long value: "+b.longValue()); System.out.println(“long value:”+ b.longValue());
--> long value: 4830110600354856960 - > long值:4830110600354856960
http://download.oracle.com/javase/1,5,0/docs/api/java/math/BigInteger.html#longValue%28%29 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. 它返回低64位,因此最后64位必须高于Long.MAX_VALUE才能产生负值。
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). 您的字符串表示形式是有符号长整数,但是作为无符号字符串呈现给BigInteger(符号在字符串的开头使用“ - ”表示)。
The String representation consists of an optional minus sign followed by a sequence of one or more digits in the specified radix. 字符串表示由一个可选的减号后跟一个指定基数中的一个或多个数字的序列组成。
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. 我认为最好的答案是将您的字符串转换为字节数组并使用BigInteger(byte [] val)实例化,它将根据二进制补码识别负数或正数。 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. 你得到最不重要的位。
If you always have 128-bit numbers and assume the highest bit is your sign then you can use the following lines: 如果您始终拥有128位数字并假设最高位是您的符号,那么您可以使用以下行:
BigInteger neg = BigInteger.ONE.shiftLeft(127);
BigInteger b = new BigInteger("80000000000000004308000000000000", 16);
if(b.compareTo(neg) >= 0) {
b = neg.subtract(b);
}
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. 注意: b.longValue()
仅在位数适合long时才适用,而对于如此大的数字可能不是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.