将双精度值设置为特定索引中的字节数组
Set double value to byte array in specific index
我用 C# 编程。
我正在寻找将双精度(或任何原始)值设置为特定偏移量的现有字节数组的有效方法。
我熟悉 BitConverter.GetBytes 和 Buffer.BlockCopy 命令。
我正在寻找使我能够将原始值直接设置为数组中特定字节偏移量的函数,而无需分配新的内存
像这样的代码
public unsafe static void SetBytes(int value,byte[] output,int index)
{
fixed(byte* b = output)
*((int*)b+index) = value;
}
普通版:
public unsafe static void SetBytesArray(int value, byte[] output, int index)
{
byte[] byteValue = BitConverter.GetBytes(value);
Buffer.BlockCopy(byteValue, 0, output, index * 4, 4);
}
论坛里的朋友让我在上面的极限版本和普通版本之间添加测量压缩
我创建了 1000 字节的数组,在每个循环中我用常量 int 值填充所有数组。
我重复上面的动作10000次,我用秒表测量时间。
一个周期的平均时间:
极端 - 0.004 个刻度 (SetBytes)
常规 - 0.028 个刻度 (SetBytesArray)
谢谢,
马克
据我所知,你所拥有的应该可以工作(一旦你修复了编译错误)。
例如:
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;
}
}
}
[编辑:更改为使用字节偏移而不是 int 偏移]
我用 C# 编程。
我正在寻找将双精度(或任何原始)值设置为特定偏移量的现有字节数组的有效方法。 我熟悉 BitConverter.GetBytes 和 Buffer.BlockCopy 命令。 我正在寻找使我能够将原始值直接设置为数组中特定字节偏移量的函数,而无需分配新的内存 像这样的代码
public unsafe static void SetBytes(int value,byte[] output,int index)
{
fixed(byte* b = output)
*((int*)b+index) = value;
}
普通版:
public unsafe static void SetBytesArray(int value, byte[] output, int index)
{
byte[] byteValue = BitConverter.GetBytes(value);
Buffer.BlockCopy(byteValue, 0, output, index * 4, 4);
}
论坛里的朋友让我在上面的极限版本和普通版本之间添加测量压缩
我创建了 1000 字节的数组,在每个循环中我用常量 int 值填充所有数组。 我重复上面的动作10000次,我用秒表测量时间。
一个周期的平均时间:
极端 - 0.004 个刻度 (SetBytes)
常规 - 0.028 个刻度 (SetBytesArray)
谢谢,
马克
据我所知,你所拥有的应该可以工作(一旦你修复了编译错误)。
例如:
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;
}
}
}
[编辑:更改为使用字节偏移而不是 int 偏移]