3

I was wondering if it's possible to convert a signed Hexadecimal (negative) to its corresponding decimal value.

Pang
10.2k146 gold badges87 silver badges126 bronze badges
asked Jun 20, 2016 at 8:39
3
  • Assuming your input is a String starting in '-' and containing only hex digits, Integer.parseInt(input,16) will work. Commented Jun 20, 2016 at 8:41
  • show us what you have so far Commented Jun 20, 2016 at 8:49
  • What I am doing right now is that I take the negative hex and convert it to binary. I have a 2's compliment binary to decimal. It does work on small values. But when I try to convert large values like -4000(assuming hex) it is not correct. Commented Jun 20, 2016 at 9:00

1 Answer 1

5

I assume that you have a hexadecimal value in form of a String.

The method parseInt(String s, int radix) can take a hexadecimal (signed) String and with the proper radix (16) it will parse it to an Integer.

int decimalInt = parseInt(hexaStr, 16);

the solution above only works if you have numbers like -FFAA07BB... if you want the Two's complements you'll have to convert it yourself.

String hex = "F0BDC0";
// First convert the Hex-number into a binary number:
String bin = Integer.toString(Integer.parseInt(hex, 16), 2);
// Now create the complement (make 1's to 0's and vice versa)
String binCompl = bin.replace('0', 'X').replace('1', '0').replace('X', '1');
// Now parse it back to an integer, add 1 and make it negative:
int result = (Integer.parseInt(binCompl, 2) + 1) * -1;

or if you feel like having a one-liner:

int result = (Integer.parseInt(Integer.toString(Integer.parseInt("F0BDC0", 16), 2).replace('0', 'X').replace('1', '0').replace('X', '1'), 2) + 1) * -1;

If the numbers get so big (or small), that an Integer will have an overflow, use Long.toString(...) and Long.parseLong(...) instead.

answered Jun 20, 2016 at 8:43
Sign up to request clarification or add additional context in comments.

3 Comments

I tried it and unfortunately, it returns an unsigned integer(15777216). My hex value is "F0BDC0" which should be -1000000.
@Jujumancer I've edited my post... that self-made solution should work for you... But be careful this solution treats every number as a negative number, even if it would be positive! You'll have to determine whether the number is negative by yourself and either use the upper or the lower solution
Thank you. I''ll check it out with other values as well. I'll be using your method just for signed hex values. Cheers

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.