C# 和java 串口传输乱码问题
因为C#和java的编码方式不同,转码后中文出现乱码
解决方案:先编码成base64,传输后解码,两边是一样的,只给出java的代码
1、解码
//dataByte是串口监听接收的byte[]
byte[] decoded = Base64.getDecoder().decode(dataByte);
2、把解码的数组转16进制字符串
/**
* 字节数组转hex字符串
* @param b
* @return
*/
public String printHexString(byte[] b) {
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sbf.append(hex.toUpperCase());
}
return sbf.toString().trim();
}
3、将16进制字符串转码成中文字符串
/**
* 16进制转换成为string类型字符串(中文无乱码)
* @param s
* @return
*/
public static String hexToStringGBK(String s) {
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e){
e.printStackTrace(); return "";
}
} try {
s = new String(baKeyword, "GBK");
} catch (Exception e1){
e1.printStackTrace(); return "";
}
return s;
}
更新一种最简单的方案231109:
原来想得比较复杂,用base64的方式去规避,实际两边数据统一成utf-8再发送就行了,代码随便百度下都有,就不贴了。。。