2012-01-29 14 views
1

これは多分あなたは、バイナリを使用したいシリアライズマニュアルXML(デ)のことを思い出す、次の擬似コードC#のバイト配列アセンブリ

//Step one, how do I WriteInt, WriteDouble, WritString, etc to a list of bytes? 
List<byte> mybytes = new List<byte>(); 
BufferOfSomeSort bytes = DoSomethingMagical(mybytes); 
bytes.WriteInt(100); 
bytes.WriteInt(120); 
bytes.WriteString("Hello"); 
bytes.WriteDouble("3.1459"); 
bytes.WriteInt(400); 


byte[] newbytes = TotallyConvertListOfBytesToBytes(mybytes); 


//Step two, how do I READ in the same manner? 
BufferOfAnotherSort newbytes = DoSomethingMagicalInReverse(newbytes); 
int a = newbytes.ReadInt();//Should be 100 
int b = newbytes.ReadInt();//Should be 120 
string c = newbytes.ReadString();//Should be Hello 
double d = newbytes.ReadDouble();//Should be pi (3.1459 or so) 
int e = newbytes.ReadInt();//Should be 400 

答えて

3

私はここBinaryReader/BinaryWriterを使用します。

// MemoryStream can also take a byte array as parameter for the constructor 
MemoryStream ms = new MemoryStream(); 
BinaryWriter writer = new BinaryWriter(ms); 

writer.Write(45); 
writer.Write(false); 

ms.Seek(0, SeekOrigin.Begin); 

BinaryReader reader = new BinaryReader(ms); 
int myInt = reader.ReadInt32(); 
bool myBool = reader.ReadBoolean(); 

// You can export the memory stream to a byte array if you want 
byte[] byteArray = ms.ToArray(); 
+0

優秀!これは私が必要としていたものです! –

3

に示されているように私は、/ dissasembleバイトのデータを組み立てることができるようにしたいと思いますシリアライズできるオブジェクトがある場合はシリアライズしますか、それとも単なる「アイテムの束」ですか? はHERESにあなたがにBinaryFormatterクラスとコードスニペットで何ができるか記述するリンク:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.80).aspx


EDIT

[Serializable] 
public class DummyClass 
{ 
    public int Int1; 
    public int Int2; 
    public string String1; 
    public double Double1; 
    public int Int3; 
} 

void BinarySerialization() 
{ 
    MemoryStream m1 = new MemoryStream(); 
    BinaryFormatter bf1 = new BinaryFormatter(); 
    bf1.Serialize(m1, new DummyClass() { Int1=100,Int2=120,Int3=400,String1="Hello",Double1=3.1459}); 
    byte[] buf = m1.ToArray(); 

    BinaryFormatter bf2 = new BinaryFormatter(); 
    MemoryStream m2 = new MemoryStream(buf); 
    DummyClass dummyClass = bf2.Deserialize(m2) as DummyClass; 
} 
+0

これはIDと文字列を含む単純なネットワーク信号です。あなたが投稿した内容は興味深いようですが、ストリームリストにはバイトリストではなく、ストリームには書き込まれています。それをバイトリストに入れる方法はありますか? –

+0

あなたは、すべてをMemoryStreamにシリアル化し、そのストリーム上で "ToArray"を呼び出すことができます。それはあなたが必要とするものですか? – stylefish

+1

@stylefishさん、あなたが好きではない場合は私の編集を削除することができます –