Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ASCII to hexadecimal values in java

Tags:

java

How to convert ASCII to hexadecimal values in java.

For example:

ASCII: 31 32 2E 30 31 33

Hex: 12.013

like image 499
lakshmi Avatar asked Apr 26 '10 05:04

lakshmi


People also ask

Why do we convert ASCII to hex?

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.

How do you write hexadecimal in Java?

In Java programs, hexadecimal numbers are written by placing 0x before numbers.


2 Answers

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 "
like image 146
polygenelubricants Avatar answered Nov 14 '22 23:11

polygenelubricants


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);
like image 43
Michael Aaron Safyan Avatar answered Nov 15 '22 00:11

Michael Aaron Safyan