C# byte[] 转换成string 时数组越界! 请大侠速来帮忙!

2024-11-23 22:57:40
推荐回答(2个)
回答1:

// copyright @ quark
// date: 2010-10-21

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace BaiduTest
{
static class Program
{

public struct sys_UserTable
{
public int UserID;
public string U_LoginName;
}

static void Main()
{
// 测试数据
sys_UserTable table = new sys_UserTable();
table.UserID =12345;
table.U_LoginName = "test name";

// 按照你给的逻辑得到数据包
byte[] data = GetBytesOfUserTable(table);

sys_UserTable resultTable = GetUserInfomation(data);

Console.WriteLine(resultTable.UserID);
Console.WriteLine(resultTable.U_LoginName);

Console.ReadKey();
}

public static sys_UserTable GetUserInfomation(byte[] bytes)
{
// 因为你的包格式固定,所以我定义一些常量,表示各个数据的起始位置
const int USER_ID_INDEX = 4;
const int USER_NAME_INDEX = 8;
sys_UserTable table = new sys_UserTable();

if (bytes.Length < 12)
{
return table;
}

// 因为你的第一个UserID可能会改成存长度,所以我取第4到第7个字节
byte[] userIDBytes = new byte[sizeof(int)];
Array.Copy(bytes, USER_ID_INDEX, userIDBytes, 0, userIDBytes.Length);
table.UserID = BitConverter.ToInt16(userIDBytes, 0);

// 取名字的长度
byte[] nameLengthBytes = new byte[sizeof(int)];
Array.Copy(bytes, USER_NAME_INDEX, nameLengthBytes, 0, nameLengthBytes.Length);
int nameLength = BitConverter.ToInt16(nameLengthBytes, 0);

if (12 + nameLength > bytes.Length)
{
return table;
}

// 取名字
byte[] nameBytes = new byte[nameLength];
Array.Copy(bytes, USER_NAME_INDEX + nameLengthBytes.Length, nameBytes, 0, nameBytes.Length);
table.U_LoginName = Encoding.ASCII.GetString(nameBytes);

return table;

}

public static byte[] GetBytesOfUserTable(sys_UserTable userTable)
{
int place = 0;
byte[] data = new byte[2048];

//UserID
Buffer.BlockCopy(BitConverter.GetBytes(userTable.UserID), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(BitConverter.GetBytes(12345), 0, data, place, 4);
place += 4;

//U_LoginName
byte[] bsU_LoginName = Encoding.ASCII.GetBytes(userTable.U_LoginName);
Buffer.BlockCopy(BitConverter.GetBytes(bsU_LoginName.Length), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(bsU_LoginName, 0, data, place, bsU_LoginName.Length);
place += bsU_LoginName.Length;

return data;

}

}
}

回答2:

数组下标改小一个。