- 題名: ArrayListの使い方について
- 日時: 2006/09/06 13:39:24
- ID: 17456
- この記事の返信元:
- (なし)
- この記事への返信:
- [17457] Re[1]: ArrayListの使い方について2006/09/06 13:58:02
- ツリーを表示
こんにちは。
私も実行してみましたが、確かに 1 だけ出力されますね。
原因はここにあると思います。
Array.Copy(data, i * 2, temp, 0, 2);
tempList.Add(temp);
ここで temp を tempList に Add していますが、temp の領域確保はループ外で
1度しか行われていません。なので、tempList が指している temp は全て同じも
のになります。
Array.Copy の前に
temp = new byte[2];
を追加してみてください。
ちなみに
data = BitConverter.GetBytes(0x0001000200030004);
これだと「1,2,3,4」ではなく「4,3,2,1」になりませんか?
分類:[.NET]
お世話になっております。 8byteのバイト配列を2byteづつ取り出してList<byte[]>で追加していきたいのですが、思ったように追加されません。 下記で示すコードでいうと ・期待値は 1,2,3,4 のようにListに追加しているつもりなのですが、結果としては 1,1,1,1 となっています。 どのようにすれば、順番どおりに追加されるのでしょうか? ご教授お願いします。 ----------------------------------- byte[] data = new byte[8]; data = BitConverter.GetBytes(0x0001000200030004); short s; byte[] temp = new byte[2]; List<byte[]> tempList = new List<byte[]>(); for (int i = 0; i < 4; i++) { Array.Copy(data, i * 2, temp, 0, 2); tempList.Add(temp); s = BitConverter.ToInt16(temp, 0); string str = Convert.ToString(s, 16).PadLeft(2, '0'); Console.WriteLine(str);//抜き出したtempは1,2,3,4のように抜き出せているようです。 } Console.WriteLine("\r\n ------------ \r\n"); short test; string test_str; foreach(byte[] bytes in tempList) { test = BitConverter.ToInt16(bytes, 0); test_str = Convert.ToString(test, 16); Console.WriteLine( test_str); }