我有一个需要转换为ASCII并打印的十六进制字符串。在调试时,我可以看到正确的值但是当我尝试打印ASCII时,它会忽略它并移动到下一个。有没有办法可以将所有不可打印的字符替换为点(。)。这是我的片段:
import javax.xml.bind.DatatypeConverter;
byte[] out = toByteArray("0000005401F40000D9E3C60500000000002000000000000000D7C8F10000000000000000000000004040404040404040D9E3C600E9C7C9F0F0F0F1F1E5D9C1D1C1D54040F0F0F14BF0F0F14BF0F0F14BF0F0F100"); // Input Hex String
System.out.println("ASCII: " + out); // Prints [B@15db9742
String hex = toHexString(out);
System.out.println("Hex: " + hex); // Prints the hex - 00000054 exactly
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
答案 0 :(得分:2)
import java.util.Arrays;
import javax.xml.bind.DatatypeConverter;
public class Main {
public Main() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
byte[] out = toByteArray("0000005401F40000D9E3C60500000000002000000000000000D7C8F10000000000000000000000004040404040404040D9E3C600E9C7C9F0F0F0F1F1E5D9C1D1C1D54040F0F0F14BF0F0F14BF0F0F14BF0F0F100"); // Input Hex String
System.out.println("ASCII: " + Arrays.toString(out));
String hex = toHexString(out);
System.out.println("Hex: " + hex); // Prints the hex - 00000054 exactly
}
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
}
<强>输出强>
替换的例子:
//non-ASCII
String yourstring = Arrays.toString(out).replaceAll("[^\\x00-\\x7F]", ".");
//non-printable characters
String yourstring = Arrays.toString(out).replaceAll("\\p{C}", ".");