1

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 ?

user8012596
  • 693
  • 1
  • 8
  • 16

1 Answers1

1

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.

Balastrong
  • 4,336
  • 2
  • 12
  • 31
  • I dont get you isnt that I am using parseLong ready ? – user8012596 May 29 '20 at 19:17
  • so should I use .intValue() will that cover all the big number and do it correctly ? – user8012596 May 29 '20 at 19:19
  • just wondering you wrote this "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." so it must pass the "-" manually is it ? – user8012596 May 29 '20 at 19:20
  • If you pass `-F` returns `-15`, if you pass `F` it's `16`. You can try it as well on your machine :) – Balastrong May 29 '20 at 19:22
  • yes I tried it works like you said. So I guess I will accept your answer Long.valueOf("FF44C5EC",16).intValue(). Will be able to cover big number ? – user8012596 May 29 '20 at 19:23