检索由BlockCopy压缩的数组



我有两种类型的List:一种是int元素的List,另一种是bool元素的List。要将这些列表传递给服务器,我必须执行以下操作:

using(MemoryStream m = new MemoryStream()){
  using(BinaryWriter writer = new BinaryWriter(m)){
    byte[] bytesIntList = new byte[IntList.Count * sizeof(int)];
    Buffer.BlockCopy(IntList.ToArray(), 0, bytesIntList, 0, bytesIntList.Length);
    writer.Write(Convert.ToBase64String(bytesIntList));
    byte[] bytesBoolList = new byte[BoolList.Count * sizeof(bool)];
    Buffer.BlockCopy(BoolList.ToArray(), 0, bytesBoolList, 0, bytesBoolList.Length);
    writer.Write(Convert.ToBase64String(bytesBoolList));
  }
  byte[] data = m.ToArray();
  return data;
}

现在,我想知道如何做相反的过程:接收这些列表:

using (MemoryStream m = new MemoryStream(data)){
  using (BinaryReader reader = new BinaryReader(m)){
    byte[] bytesIntList = Convert.FromBase64String(reader.ReadString());
    byte[] bytesBoolList = Convert.FromBase64String(reader.ReadString());
    List<int> newIntList = ??? //what do I have to do here?
    List<bool> newBoolList = ??? //what do I have to do here?
  }
}

如果你有其他建议传递列表,欢迎!

这里的问题是,虽然有一种方法可以很容易地从字节数组转换为整型数组,但是没有一种方法可以从字节数组转换为整型数组。

您必须首先将其转换为数组(就像保存它时所做的那样),或者您必须一次遍历字节缓冲区一个int。

首先转换为数组如下所示:

byte[] data = new byte[1000]; // Pretend this is your read-in data.
int[] result = new int[data.Length/sizeof(int)];
Buffer.BlockCopy(data, 0, result, 0, data.Length);
List<int> list = result.ToList();

我认为一次将其转换为int会更好,因为你不需要先将其转换为数组:

byte[] data = new byte[1000]; // Pretend this is your read-in data.
List<int> list = new List<int>();
for (int i = 0, j = 0; j < data.Length; ++i, j += sizeof(int))
    list.Add(BitConverter.ToInt32(data, j));

要将字节数组转换为bool数组,可以这样做:

byte[] data = new byte[1000]; // Pretend this is your read-in data.
List<bool> list = new List<bool>();
for (int i = 0, j = 0; j < data.Length; ++i, j += sizeof(bool))
    list.Add(BitConverter.ToBoolean(data, j));

或者,对于将字节转换为bool,我们可以使用Linq(将字节转换为int并不那么容易):

byte[] data = new byte[1000]; // Pretend this is your read-in data.
List<bool> list = (from b in data select b != 0).ToList();

或者使用方法代替查询语法(如果您喜欢的话):

byte[] data = new byte[1000]; // Pretend this is your read-in data.
List<bool> list = data.Select(b => b != 0).ToList();

相关内容

  • 没有找到相关文章

最新更新