Mo Joe Mo Joe - 25 days ago 7
Java Question

String hex to Dec Int/converting positiv to negativ

i´m a programming newbie so please be nice :)
I just wrote a programm which convert a hex String to dec int. I´ve testet it with "negative" hex, and some values are right and some are wrong. I can´t really resolve the issue with the wrong output.

here´s my code:

String abc = "0123456789ABCDEF";
String hexString = "-ffad";
int decResult = 0;
//int endRes = 0;

hexString = hexString.toUpperCase();

for(int i = 0; i < hexString.length(); i++)
{
if(hexString.contains("-"))
{
hexString = hexString.replace("-", "");
char res = hexString.charAt(i);
int d = abc.indexOf(res);
decResult = (16*decResult + d)*(-1);
}
else
{
char res = hexString.charAt(i);
int d = abc.indexOf(res);
decResult = ((16*decResult) + d)*1;
}
}
System.out.println(decResult);

Answer

since you are doing this

if(hexString.contains("-"))

for EVERY char in the hexString string then the final sign of the convertion will be calculated as

  • negative if hexString.length() is odd,
  • positive otherwise.

a working solution improved can be:

    hexString = hexString.toUpperCase();
    int sign = hexString.charAt(0) == '-' ? -1 : 1;
    hexString = hexString.replace("-", "");
    decResult = Integer.parseInt(hexString, 16) * sign;
    System.out.println(decResult);
Comments