一、通过String类的getBytes()方法将String转换成byte。
String string = "abcdefghijklmn";
byte[] bytes = string.getBytes();
二、通过String构造函数将byte数组转换成String。
byte[] cmd_bytes ={0x61,0x62,0x63,0x64};
String str_cmd = new String(cmd_bytes);
三、byte 打印成十六进制方法
public static void BytePrintAsString(byte [] byteArray) {
for (int i = 0; i < byteArray.length; i++) {
String hex = Integer.toHexString(byteArray[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print("0x"+hex.toUpperCase()+";");
}
System.out.println("");
}
四、实例测试
4.1 java代码
public class Main {
public static void BytePrintAsString(byte [] byteArray) {
for (int i = 0; i < byteArray.length; i++) {
String hex = Integer.toHexString(byteArray[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print("0x"+hex.toUpperCase()+";");
}
System.out.println("");
}
public static void main(String[] args) {
String string = "abcdefghijklmn";
byte[] bytes = string.getBytes();
BytePrintAsString(bytes);
System.out.println("*************************");
byte[] cmd_bytes ={0x61,0x62,0x63,0x64};
String str_cmd = new String(cmd_bytes);
System.out.println(str_cmd);
System.out.println("*************************");
byte[] data_bytes ={0x61,0x62,0x01,0x64};
String str_data = new String(data_bytes);
System.out.println(str_data);
System.out.println("*************************");
byte[] data_str_bytes = str_data.getBytes();
BytePrintAsString(data_str_bytes);
}
}
4.2 java代码运行输出结果如下,注意第五行有个乱码,因为0x01不属于字符。
0x61;0x62;0x63;0x64;0x65;0x66;0x67;0x68;0x69;0x6A;0x6B;0x6C;0x6D;0x6E;
*************************
abcd
*************************
abd
*************************
0x61;0x62;0x01;0x64;
sandbox> exited with status 0
五、trim()方法是一个内置函数,可以消除前导和尾随空格
public String trim() {
int len = length();
int st = 0;
while ((st < len) && (charAt(st) <= ' ')) {
st++;
}
while ((st < len) && (charAt(len - 1) <= ' ')) {
len--;
}
return ((st > 0) || (len < length())) ? substring(st, len) : this;
}
六、参考文章
Java String trim()方法的详解_Smile sea breeze的博客-CSDN博客
java - Eliminate default zeros while creating string from byte array - Stack Overflow
Java byte[] 和 String互相转换_java byte转string_BasicLab基础架构实验室的博客-CSDN博客