Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
Earlz Avatar asked Dec 22 '22 04:12

Earlz


2 Answers

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();
    }
like image 108
Hans Passant Avatar answered Jan 05 '23 16:01

Hans Passant


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();
like image 21
mmx Avatar answered Jan 05 '23 16:01

mmx