Java的Long.parseLong在二进制补码方面不能给出正确的值。

huangapple go评论69阅读模式
英文:

Java Long.parseLong does not give correct value in terms of 2's complement

问题

我有以下代码,我在其中进行从十六进制到十进制的转换。
Long.parseLong("FF44C5EC", 16).
我得到的输出是4282697196
但根据正确情况,它应该是一个负数。我还需要做什么来获得使用二进制补码的正确转换?

英文:

I have the following codes where I am doing conversion from hex to decimal.
Long.parseLong("FF44C5EC",16).
The output I get is this 4282697196
But by right it should be a negative number. What else should I do to get the correct conversion with 2's complement ?

答案1

得分: 1

parseLong 返回一个有符号的 long,但是“有符号”意味着它可以处理负数,如果你传递一个以 - 开头的字符串,而不是它了解二进制的补码。

将字符串参数解析为由第二个参数指定的基数中的有符号 long。字符串中的字符必须都是指定基数的数字(由Character.digit(char,int)是否返回非负值来确定),除非第一个字符可以是ASCII减号'-''\u002D')以指示负值或ASCII加号'+''\u002B')以指示正值。返回结果的long值。

一个解决方案可以是:

Long.valueOf("FF44C5EC",16).intValue()

这将打印 -12270100,与您的期望一致。

英文:

parseLong returns a signed long, but by "signed" it means that it can handle negative numbers if you pass a string starting with -, not that it knows the 2's complement.

> Parses the string argument as a signed long in the radix specified by
> the second argument. The characters in the string must all be digits
> of the specified radix (as determined by whether Character.digit(char,
> int) returns a nonnegative value), except that the first character may
> be an ASCII minus sign '-' ('\u002D') to indicate a negative value or
> an ASCII plus sign '+' ('\u002B') to indicate a positive value. The
> resulting long value is returned.

A solution could be:

Long.valueOf("FF44C5EC",16).intValue()

That prints -12270100 as you expect.

huangapple
  • 本文由 发表于 2020年5月30日 03:03:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/62093036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定