十六进制到Ascii转换

时间:2014-05-06 09:03:28

标签: android sockets hex ascii android-bluetooth

我在阅读时从蓝牙插座获得了十六进制(Example: 0x61 0x62 0x63)。

我想获得相应的ASCII(Example: a b c)。

如何进行转换?

我试过了:

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();

2 个答案:

答案 0 :(得分:2)

我的解决方案(已测试):

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

<强> [编辑]

要摆脱 ,只需将0x00替换为0x30 这是“0”的ASCII表示

类似的东西:

final String str_in =
    "0x56 0x49 0x4e 0x31 0x32 0x33 0x46 0x4f 0x52 " +
    "0x44 0x54 0x52 0x55 0x43 0x4b 0x00 0x38".replace("0x00", "0x30");

答案 1 :(得分:1)

这样的事情应该有效:

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();