Search code examples
c#arraysbitconverter

Is there a less painful way to GetBytes for a buffer not starting at 0?


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?


Solution

  • 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();
        }