2012-01-29 66 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