2012-01-29 34 views
1

我希望能夠組裝/ dissasemble字節的數據,如下面的僞代碼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

優秀!這正是我需要的! – 2012-01-29 00:13:23

3

這讓我想起了手動XML的(DE)證實序列化也許你想使用二進制序列化,如果你有一個對象,你可以序列化,或者它只是「一堆項目」,你想寫? 繼承人鏈接描述你可以用BinaryFormatter類和代碼片段做什麼:

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


編輯

[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和字符串。你發佈的內容看起來很有趣,但我注意到它寫入一個流而不是一個字節列表,反之亦然。有什麼辦法可以把它放到一個字節列表中嗎? – 2012-01-29 00:11:30

+0

您可以將所有內容序列化到MemoryStream中,然後在該流上調用「ToArray」。你需要什麼? – stylefish 2012-01-29 00:14:53

+1

@stylefish,你可以刪除我的編輯,如果你不喜歡它 – 2012-01-29 00:44:39