I have a Hex string that needs to be converted to ASCII and be printed. While debugging, I can see the correct values but when I try to print the ASCII, it ignores it and moves to the next. Is there a way I can replace all the non-printable characters as dot(.). Here is my snippet:
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);
}
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);
}
}
Output
Examples of replacing :
//non-ASCII
String yourstring = Arrays.toString(out).replaceAll("[^\\x00-\\x7F]", ".");
//non-printable characters
String yourstring = Arrays.toString(out).replaceAll("\\p{C}", ".");
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.