Domanda

I got Hex (Example: 0x61 0x62 0x63) from Bluetooth socket on read.

I want to get its corresponding ASCII (Example: a b c).

How to do that conversion?

I tried:

String s = "0x56 0x49 0x4e 0x31 0x32 0x33 0x46 0x4f 0x52 
            0x44 0x54 0x52 0x55 0x43 0x4b 0x00 0x38";
StringBuilder sb = new StringBuilder(s.length() / 2);
for (int i = 0; i < s.length(); i+=2) {
    String hex = "" + s.charAt(i) + s.charAt(i+1);
    int ival = Integer.parseInt(hex, 16);
    sb.append((char) ival);
}
String string = sb.toString();
È stato utile?

Soluzione 2

Something like this should work:

String s = "0x56 0x49 0x4e 0x31 0x32 0x33 0x46 0x4f 0x52 
        0x44 0x54 0x52 0x55 0x43 0x4b 0x00 0x38";
StringBuilder sb = new StringBuilder();
String[] components = s.split(" ");
for (String component : components) {
    int ival = Integer.parseInt(component.replace("0x", ""), 16);
    sb.append((char) ival);
}
String string = sb.toString();

Altri suggerimenti

My solution (tested):

final String str_in =
    "0x56 0x49 0x4e 0x31 0x32 0x33 0x46 0x4f 0x52 " +
    "0x44 0x54 0x52 0x55 0x43 0x4b 0x00 0x38";
final String[] arr = str_in.split(" ");
String str_out = "";

// To decimal.
//for (final String s : arr)
//{
//  final String chr = " " + Integer.parseInt(s.replace("0x", ""), 16);
//  str_out += chr;
//}
//System.out.println(str_out); // str_out = "86 73 78 49 50 51 70 79 82 68 84 82 85 67 75 0 56"

// To ASCII
for (final String s : arr)
{
    final char chr = (char) Integer.parseInt(s.replace("0x", ""), 16);
    str_out += " " + chr;
}
System.out.println(str_out); // str_out = "V I N 1 2 3 F O R D T R U C K �� 8" // �� is because of 0x00

[EDIT]

To get rid of the �� , just replace 0x00 with 0x30.
This is the ASCII representation for "0"

Something like:

final String str_in =
    "0x56 0x49 0x4e 0x31 0x32 0x33 0x46 0x4f 0x52 " +
    "0x44 0x54 0x52 0x55 0x43 0x4b 0x00 0x38".replace("0x00", "0x30");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top