I am having to deal with raw bytes in a project and I need to basically do something like this
byte[] ToBytes(){
byte[] buffer=new byte[somelength];
byte[] tmp;
tmp=BitConverter.GetBytes(SomeShort);
buffer[0]=tmp[0];
buffer[1]=tmp[1];
tmp=BitConverter.GetBytes(SomeOtherShort);
buffer[2]=tmp[0];
buffer[3]=tmp[1];
}
I feel like this is so wrong yet I can't find any better way of doing it. Is there an easier way?
BinaryWriter is very efficient:
byte[] ToBytes() {
var ms = new MemoryStream(somelength);
var bw = new BinaryWriter(ms);
bw.Write(SomeShort);
bw.Write(SomeOtherShort);
return ms.ToArray();
}
You don't need to initialize tmp
to a new array. BitConverter.GetBytes
creates a new array and returns it for you. There's not much you can do about GetBytes
but you can use methods like Buffer.BlockCopy
to simplify the copy operation.
If you're not doing this in a performance-critical piece of code, you can go a bit LINQy and do things like:
IEnumerable<byte> bytes = BitConverter.GetBytes(first);
bytes = bytes.Concat(BitConverter.GetBytes(second));
bytes = bytes.Concat(BitConverter.GetBytes(third));
// ... so on; you can chain the calls too
return bytes.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With