Psycho - 6 months ago 11
Java Question

# Negative int to hexadecimal conversion

I am converting some integers to hexadecimals but the problem i have is when i pass a negative value to convert it to hex.

Example:

``````String satpos = "13.0";
String satposs=satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
String nids = Integer.toHexString(satposition);
String finished = nids+"0000";
``````

Application returns "820000" in this case and that is the correct value i need.
But if i pass:

``````String satpos = "-7.0";
String satposs=satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
String nids = Integer.toHexString(satposition);
String finished = nids+"0000";
``````

Application returns "ffffffba0000" but i should get "DCA0000"

Any help is appreciated.

Based on a comment by Andreas, here is a test program that prints the values you want:

``````public class Test {
public static void main(String[] args) {
convert("13.0");
convert("-7.0");
}

private static void convert(String satpos) {
String satposs = satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
if (satposition < 0) {
satposition += 3600;
}
String nids = Integer.toHexString(satposition);
String finished = nids + "0000";
System.out.println(finished);
}

}
``````

If the angle is negative, add 3600 because the angle is in tenths of a degree.

Source (Stackoverflow)