某些协议,必须用16进制。
//适用于英文,日文,中文。
public static void demoChangeStringToHex(final String inputString) {
int changeLine = 1;
String s = "Convert a string to HEX/こんにちは/你好";
if (inputString != null) {
s = inputString;
}
System.out.println(s);
for (int i = 0; i < s.length(); i++) {
byte[] ba = s.substring(i, i + 1).getBytes();
// & 0xFF for preventing minus
String tmpHex = Integer.toHexString(ba[0] & 0xFF);
System.out.print("0x" + tmpHex.toUpperCase());
System.out.print(" ");
if (changeLine++ % 8 == 0) {
System.out.println("");
}
// Multiply byte according
if (ba.length == 2) {
tmpHex = Integer.toHexString(ba[1] & 0xff);
System.out.print("0x" + tmpHex.toUpperCase());
System.out.print(" ");
if (changeLine++ % 8 == 0) {
System.out.println("");
}
}
}
System.out.println(""); // change line
System.out.println(""); // change line
}