Georges Oates Larsen
Georges Oates Larsen

Reputation: 7102

C# Byte array assembly

I would like to be able to assemble/dissasemble byte data, as demonstrated in the following psuedocode

//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

Upvotes: 1

Views: 517

Answers (2)

stylefish
stylefish

Reputation: 571

this reminds me of manual XML (de)serializing maybe you want to use the binary serialization if you have an object you can serialize or is it just "a bunch of items" you want to write? heres a link describing what you can do with the BinaryFormatter class and a code snippet:

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

Upvotes: 1

ken2k
ken2k

Reputation: 48985

I would use BinaryReader/BinaryWriter here.

// 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();

Upvotes: 3

Related Questions