字节数组转字符串

本文介绍了一个Java方法,该方法用于将字节数组转换为字符串,并使用UTF-8编码进行解码。该方法首先查找字节数组中第一个空字符的位置,然后将从开始到该位置的数据截取出来并转换成字符串。
public String byteTOString(byte[] src) {
	int idx = 0;
	for (idx = 0; idx < src.length; idx++) {
		if (src[idx] == (byte) 0) {
			break;
		}
	}
	try {
		return new String(src, 0, idx, "UTF-8");
	} catch (Exception e) {
		e.printStackTrace();
		return new String(src, 0, idx);
	}
}

 

在C#中,字节数组字符串出现乱码,可根据不同场景采用不同的解决办法: - **Unity C#字节数组字符串中文乱码**:若在Unity C#中遇到字节数组字符串时中文乱码且使用`System.Text.Encoding.Default.GetString(str)`无效,由于不清楚后端发送的编码方式,可尝试使用不同的编码格式进行换,例如UTF - 8、GB2312等。示例代码如下: ```csharp byte[] byteArray = new byte[] { /* 字节数组数据 */ }; string strUTF8 = System.Text.Encoding.UTF8.GetString(byteArray); string strGB2312 = System.Text.Encoding.GetEncoding("GB2312").GetString(byteArray); ``` - **C# Socket传输中文出现乱码**:在C# Socket传输中文数据时,为避免乱码,发送方和接收方都要使用相同的编码格式。通常使用UTF - 8编码,发送方将字符串换为字节数组,接收方再将字节数组换为字符串。示例代码如下: ```csharp // 发送方 string sendMsg = "中文消息"; byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(sendMsg); // 假设socket是已连接的Socket对象 socket.Send(sendBytes); // 接收方 byte[] receiveBytes = new byte[1024]; int bytesRead = socket.Receive(receiveBytes); string receiveMsg = System.Text.Encoding.UTF8.GetString(receiveBytes, 0, bytesRead); ``` - **C# FileStream文件读写出现乱码**:使用`FileStream`读写文件时出现乱码,可使用UTF - 8编码进行读写操作。示例代码如下: ```csharp // 写文件 string msg = "中文消息"; byte[] myByte = System.Text.Encoding.UTF8.GetBytes(msg); using (FileStream fsWrite = new FileStream(@"D:\1.txt", FileMode.Append)) { fsWrite.Write(myByte, 0, myByte.Length); } // 读文件 using (FileStream fsRead = new FileStream(@"D:\1.txt", FileMode.Open)) { int fsLen = (int)fsRead.Length; byte[] heByte = new byte[fsLen]; int r = fsRead.Read(heByte, 0, heByte.Length); string myStr = System.Text.Encoding.UTF8.GetString(heByte); Console.WriteLine(myStr); Console.ReadKey(); } ``` - **C#读取mfc序列化CStringArray出现乱码**:在C#读取mfc序列化的文件,读取`CStringArray`数组出现乱码时,可使用`BinaryReader`类并指定合适的编码格式,如GB2312。示例代码如下: ```csharp using (FileStream fs = new FileStream("filePath", FileMode.Open)) { BinaryReader br = new BinaryReader(fs, System.Text.Encoding.GetEncoding("GB2312")); string str = br.ReadString(); } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值