B
Brian
What is the easiest way to convert primitives to a byte array? I tried the
BinaryFormatter serialization but it serializes objects so when I serialized
an and int it took 54 bytes instead of 4. I tried something like the
following but it won't compile (I admit I use generics a lot but haven't
written many so this may be way off):
class X<T>
{
public byte[] ToByteArray(T val)
{
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(val);
BinaryReader br = new BinaryReader(bw.BaseStream);
br.BaseStream.Position = 0;
return br.ReadBytes((int)br.BaseStream.Length);
}
}
I don't want to have an overloaded method for every primitive type. Is there
an easy way to do this...or have the overloads already been written to do
this and I am just missing it? It seems like a pretty basic task that should
be there somewhere already.
thanks
BinaryFormatter serialization but it serializes objects so when I serialized
an and int it took 54 bytes instead of 4. I tried something like the
following but it won't compile (I admit I use generics a lot but haven't
written many so this may be way off):
class X<T>
{
public byte[] ToByteArray(T val)
{
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(val);
BinaryReader br = new BinaryReader(bw.BaseStream);
br.BaseStream.Position = 0;
return br.ReadBytes((int)br.BaseStream.Length);
}
}
I don't want to have an overloaded method for every primitive type. Is there
an easy way to do this...or have the overloads already been written to do
this and I am just missing it? It seems like a pretty basic task that should
be there somewhere already.
thanks