Search code examples
javadata-conversiontwos-complement

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


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 ?


Solution

  • 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.