Is there a less painful way to getBytes for a buffer that doesn't start at 0?

I need 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 this is so wrong, but I cannot find a better way to do this. Is there an easier way?

+4
source share
5 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(); } 
+6
source

You do not need to initialize tmp for the new array. BitConverter.GetBytes creates a new array and returns it for you. Not much can be done for GetBytes , but you can use methods such as Buffer.BlockCopy to simplify the copy operation.

If you are not doing this in a performance-critical piece of code, you can go a little 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(); 
+3
source

If you know the size in advance (you have a set of value types), you can use the structure and assign your values ​​in the structure. Then use unsafe code to copy the raw bytes. I would still advise him if it is really necessary for speed. And you might think that it hurts :)

 private struct MyStruct { public short A; public short B; public MyStruct(short a, short b) { A = a; B = b; } } private unsafe byte[] UnsafeStruct(MyStruct myStruct) { byte[] buffer = new byte[4]; // where 4 is the size of the struct fixed (byte* ptr = buffer) { *((MyStruct*)ptr) = myStruct; } return buffer; } 
+1
source

Just a bit shift ...

 buffer[0]=(byte)SomeShort; buffer[1]=(byte)(SomeShort >> 8); buffer[2]=(byte)SomeOtherShort; buffer[3]=(byte)(SomeOtherShort >> 8); 

It also means that you are in complete control of the limb (in this case, little-endian)

+1
source

You can make your code a little shorter using Array.Copy, but there is no GetBytes overload or equivalent in BitConverter that puts bytes directly into your buffer.

Maybe BinaryWriter on a MemoryStream what do you want?

Note that by accepting BitConverter APIs that you don’t like, you are causing the same problem for users of your class. Instead, write a method that takes BinaryWriter and serializes your class into it, this spreads well when your class is embedded in some other object.

0
source

Source: https://habr.com/ru/post/1305266/


All Articles