简体   繁体   中英

How to convert Hexadecimal to ASCII values in java?

Thanks for your answer... I have 31 32 2E 30 31 33 6byte hexadecimal number. I want to convert 31 32 2E 30 31 33 this 6 byte hexadecimal number into 12.013 ASCII number in java.

Something like this?

byte[] bytes = {0x31, 0x32, 0x2E, 0x30, 0x31, 0x33};
String result = new String(bytes, "ASCII");
System.out.println(result);

Probably not the most elegant method but try this:

char[6] string = new char[6];
string[0] = 0x31;
string[1] = 0x32;
string[2] = 0x2E;
string[3] = 0x30;
string[4] = 0x31;
string[5] = 0x33;

String s = new String(string);

int result = Integer.parseInt(s);

Assuming that your input is an array of strings representing the digits in hex, you can do the following:

public static String convert(String[] hexDigits){
    byte[] bytes = new byte[hexDigits.length];

    for(int i=0;i<bytes.length;i++)
        bytes[i] = Integer.decode("0x"+hexDigits[i]).byteValue();

    String result;
    try {
        result = new String(bytes, "ASCII");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return result;
}

Note that the code assumes that the digits are given as valid ASCII values, with no radix specifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM