c# - BitConverter.GetBytes in place -


i need values in uint16 , uint64 byte[]. @ moment using bitconverter.getbytes, method gives me new array instance each time.

i use method allow me "copy" values existing arrays, like:

.tobytes(uint64 value, byte[] array, int32 offset); .tobytes(uint16 value, byte[] array, int32 offset); 

i have been taking .net source code ilspy, not sure how code works , how can safely modify fit requirement:

public unsafe static byte[] getbytes(long value) {     byte[] array = new byte[8];     fixed (byte* ptr = array)     {             *(long*)ptr = value;     }     return array; } 

which right way of accomplishing this?

updated: cannot use unsafe code. should not create new array instances.

you can this:

static unsafe void tobytes(ulong value, byte[] array, int offset) {     fixed (byte* ptr = &array[offset])         *(ulong*)ptr = value; } 

usage:

byte[] array = new byte[9]; tobytes(0x1122334455667788, array, 1); 

you can set offset in bytes.

if want managed way it:

static void tobytes(ulong value, byte[] array, int offset) {     byte[] valuebytes = bitconverter.getbytes(value);     array.copy(valuebytes, 0, array, offset, valuebytes.length); } 

or can fill values yourself:

static void tobytes(ulong value, byte[] array, int offset) {     (int = 0; < 8; i++)     {         array[offset + i] = (byte)value;         value >>= 8;     } } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -