How to convert ASCII to hexadecimal values ​​in java

How to convert ASCII to hexadecimal values ​​in java.

For instance:

ASCII: 31 32 2E 30 31 33

Hex: 12.013

+4
source share
2 answers

You have not converted ASCII to hexadecimal. You had char values ​​in hexadecimal, and you wanted to convert it to String , as I interpret your question.

  String s = new String(new char[] { 0x31, 0x32, 0x2E, 0x30, 0x31, 0x33 }); System.out.println(s); // prints "12.013" 

If you specify a string, and you want to print it char as a hex, here's 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 %H format string:

  for (char ch : "12.013".toCharArray()) { System.out.format("%H ", ch); } // prints "31 32 2E 30 31 33 " 
+7
source

It's not entirely clear what you are asking for, since your string "hex" is actually in decimal form. I believe that you are trying to take an ASCII string representing a double and get its value as a double, in which case use Double.parseDouble should be enough for your needs. If you need to output the hexadecimal string of a double value, you can use Double.toHexString . Note that you need to catch a NumberFormatException whenever you call one of the primitive functions to parse the primitive class.

  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);
+4
source

Source: https://habr.com/ru/post/1307982/


All Articles