How to convert ASCII to hexadecimal values in java.
For example:
ASCII: 31 32 2E 30 31 33
Hex: 12.013
In this way by using the code conversion table we can convert the characters of ASCII into Hexadecimal code. However, the ASCII code conversion is mandatory because it might be user-friendly but not machine friendly. The convenience of entering the data in the systems is easier while using a hexadecimal format.
In Java programs, hexadecimal numbers are written by placing 0x before numbers.
You did not convert ASCII to hexadecimal value. You had char
values in hexadecimal, and you wanted to convert it to a String
is how I'm interpreting your question.
String s = new String(new char[] {
0x31, 0x32, 0x2E, 0x30, 0x31, 0x33
});
System.out.println(s); // prints "12.013"
If perhaps you're given the string, and you want to print its char
as hex, then this is how to do it:
for (char ch : "12.013".toCharArray()) {
System.out.print(Integer.toHexString(ch) + " ");
} // prints "31 32 2e 30 31 33 "
You can also use the %H
format string:
for (char ch : "12.013".toCharArray()) {
System.out.format("%H ", ch);
} // prints "31 32 2E 30 31 33 "
It's not entirely clear what you are asking, since your "hex" string is actually in decimal. I believe you are trying to take an ASCII string representing a double and to get its value in the form of a double, in which case using Double.parseDouble should be sufficient for your needs. If you need to output a hex string of the double value, then you can use Double.toHexString. Note you need to catch NumberFormatException, whenever you invoke one of the primitive wrapper class's parse functions.
byte[] ascii = {(byte)0x31, (byte)0x32, (byte)0x2E, (byte)0x30, (byte)0x31, (byte)0x33}; String decimalstr = new String(ascii,"US-ASCII"); double val = Double.parseDouble(decimalstr); String hexstr = Double.toHexString(val);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With