【问题标题】:Hex to Ascii conversion十六进制到ASCII转换
【发布时间】:2014-06-22 19:25:01
【问题描述】:

我从蓝牙套接字读取十六进制 (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();

【问题讨论】:

  • 不,这不会从十六进制中删除 0x,因此不会给出正确的结果。
  • 投反对票的人应该阅读 cmets 给出的答案,并且可以解释投反对票的原因,以便我了解问题所在。

标签: android sockets hex ascii android-bluetooth


【解决方案1】:

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

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

【讨论】:

  • 我要求从Hex to Ascii 转换。但是您提出的解决方案提供了来自Hex to Decimal 的转换。请更正。
  • 抱歉,很快就会更改。
  • 我在结果中得到V I N 1 2 3 F O R D T R U C K � � 8。但是它应该是VIN123FORDTRUCK08。我尝试使用if(string.contains("??")) string.replace("??", "0");,但什么也没发生。有什么想法吗?
  • 是的。只需将原始字符串中的0x00 替换为0x30。这是“0”的 ASCII 码。
  • 为此 +1。我使用了另一种在字符之间没有空格的解决方案。这真的很有帮助。
【解决方案2】:

这样的事情应该可以工作:

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

【讨论】:

  • 我要求从Hex to Ascii 转换。但是您提出的解决方案提供了来自Hex to Decimal 的转换。请更正。
  • 不,这不会转换为十进制。无论如何,我现在纠正了一个错误,请重试。
  • 您的代码运行良好,但结果中我得到了VIN123FORDTRUCK��8。但是它应该是VIN123FORDTRUCK08。我尝试使用if(string.contains("??")) string.replace("??", "0");,但什么也没发生。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 2011-11-27
  • 2012-11-14
  • 2016-04-22
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多