Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signed Hexadecimal to decimal in Java

Tags:

java

math

hex

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

like image 799
Jujumancer Avatar asked Mar 23 '26 00:03

Jujumancer


1 Answers

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.

like image 116
ParkerHalo Avatar answered Mar 25 '26 12:03

ParkerHalo