BitConverter.GetBytes到位 [英] BitConverter.GetBytes in place
问题描述
我需要获取 UInt16
和 UInt64
中的值作为 Byte []
。目前,我正在使用 BitConverter.GetBytes
,但是此方法每次都会为我提供一个新的数组实例。
I need to get values in UInt16
and UInt64
as Byte[]
. At the moment I am using BitConverter.GetBytes
, but this method gives me a new array instance each time.
我想使用一种允许我将这些值复制到已经存在的数组的方法,例如:
I would like to use a method that allow me to "copy" those values to already existing arrays, something like:
.ToBytes(UInt64 value, Byte[] array, Int32 offset);
.ToBytes(UInt16 value, Byte[] array, Int32 offset);
我一直在使用ILSpy查看.NET源代码,但是我不太清楚此代码有效,我如何安全地对其进行修改以满足我的要求:
I have been taking a look to the .NET source code with ILSpy, but I not very sure how this code works and how can I safely modify it to fit my requirement:
public unsafe static byte[] GetBytes(long value)
{
byte[] array = new byte[8];
fixed (byte* ptr = array)
{
*(long*)ptr = value;
}
return array;
}
哪个是实现此目标的正确方法?
Which would be the right way of accomplishing this?
已更新:我不能使用不安全的代码。它不应创建新的数组实例。
Updated: I cannot use unsafe code. It should not create new array instances.
推荐答案
您可以这样做:
static unsafe void ToBytes(ulong value, byte[] array, int offset)
{
fixed (byte* ptr = &array[offset])
*(ulong*)ptr = value;
}
用法:
byte[] array = new byte[9];
ToBytes(0x1122334455667788, array, 1);
您只能以字节为单位设置偏移量。
You can set offset only in bytes.
如果您想通过托管方式做到这一点:
If you want managed way to do it:
static void ToBytes(ulong value, byte[] array, int offset)
{
byte[] valueBytes = BitConverter.GetBytes(value);
Array.Copy(valueBytes, 0, array, offset, valueBytes.Length);
}
或者您可以自己填写值:
Or you can fill values by yourself:
static void ToBytes(ulong value, byte[] array, int offset)
{
for (int i = 0; i < 8; i++)
{
array[offset + i] = (byte)value;
value >>= 8;
}
}
这篇关于BitConverter.GetBytes到位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!