2

リストには、int 要素を持つリストと bool 要素を持つリストの 2 種類があります。これらのリストをサーバーに渡すには、以下で行ったことを行う必要があります。

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?
  }
}

リストに合格するための他の提案があれば、それは大歓迎です!

4

1 に答える 1

1

ここでの問題は、バイトの配列から int の配列に簡単に移動する方法はありますが、バイトの配列からint のリストに移動する方法がないことです。

最初に配列に変換する必要があります (保存するときと同様)。または、一度に 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));

バイト配列をブール配列に変換するには、次のようにします。

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();
于 2013-05-24T14:35:24.090 に答える