byte转string乱码
时间: 2023-11-19 16:06:57 浏览: 38
当一个byte数组转换为String时,需要指定byte数组的编码方式,否则会出现乱码。例如,如果byte数组是使用UTF-8编码的,可以使用以下代码将其转换为String:
```
byte[] byteArray = ...; // byte数组
String str = new String(byteArray, "UTF-8");
```
如果byte数组使用其他编码方式,则需要将编码方式名称替换为相应的编码方式名称。
相关问题
android byte转string
可以使用Java中的String类的构造方法将byte数组转换为字符串,代码如下:
```
byte[] bytes = {97, 98, 99, 100, 101};
String str = new String(bytes);
```
这样就可以将byte数组转换为字符串了。注意,需要指定byte数组的编码方式,否则在转换过程中可能会出现乱码。例如,如果byte数组是使用UTF-8编码的,可以使用如下代码:
```
byte[] bytes = {97, 98, 99, 100, 101};
String str = new String(bytes, "UTF-8");
```
这样就可以正确地将byte数组转换为UTF-8编码的字符串了。
Java byte数组转为string乱码
当将byte数组转换为String时,需要指定字符集。如果没有指定字符集,则默认使用平台默认字符集,可能导致乱码。
以下是一个示例代码,将byte数组转换为String并指定字符集为UTF-8:
```
byte[] bytes = {72, 101, 108, 108, 111, 32, -26, -75, -84, -24, -81, -107, -23, -127, -128, -23, -127, -68};
String str = new String(bytes, "UTF-8");
System.out.println(str);
```
输出结果为:Hello 世界
如果不指定字符集,则可能会出现乱码:
```
byte[] bytes = {72, 101, 108, 108, 111, 32, -26, -75, -84, -24, -81, -107, -23, -127, -128, -23, -127, -68};
String str = new String(bytes);
System.out.println(str);
```
输出结果为:Hello ??????