I programming in C#.
I am looking for efficient way to set double (or any primitive) value into exist byte array in specific offset. I am familiar with BitConverter.GetBytes and the Buffer.BlockCopy command. I am looking for function that enable my to set the primitive value directly to specific byte offset in the array, without new memory allocation Something like this code
public unsafe static void SetBytes(int value,byte[] output,int index)
{
fixed(byte* b = output)
*((int*)b+index) = value;
}
The regular version:
public unsafe static void SetBytesArray(int value, byte[] output, int index)
{
byte[] byteValue = BitConverter.GetBytes(value);
Buffer.BlockCopy(byteValue, 0, output, index * 4, 4);
}
The friends in the forum ask me to add measure compression between the extreme version above , and to regular version
I create array of 1000 bytes, In each cycle I fill all the array with constant int value. I repeat on the above action for 10000 times , I measure the time with StopWatch.
Avg time for one cycle:
extreme - 0.004 ticks (SetBytes)
regular - 0.028 ticks (SetBytesArray)
Thanks,
Mak
As far as I can see, what you have should work (once you've fixed up the compile error).
For example:
using System;
using System.Linq;
namespace Demo
{
class Program
{
static void Main()
{
byte[] data = new byte[16];
int value = 0x12345678;
SetBytes(value, data, 5);
// This prints "0, 0, 0, 0, 0, 78, 56, 34, 12, 0, 0, 0, 0, 0, 0, 0"
Console.WriteLine(string.Join(", ", data.Select(b => b.ToString("x"))));
}
public static unsafe void SetBytes(int value, byte[] output, int index)
{
fixed (byte* b = output)
*((int*)(b + index)) = value;
}
}
}
[EDIT: Changed to work with byte offset rather than int offset]