C# 指针操作字节数组
Demo(以添加 short 类型的值为例):
- //bytes:目标字节数组; offset:目标在字节数组的位置; value:添加的类型值public static unsafe void WriteInt16ToBytes(byte[] bytes, int offset, short value)
- {
- fixed (byte* ptr = bytes)
- {
- *((short*)(ptr + offset)) = value;
- }
- }
实现思路:
1. 创建指向字节数组 bytes 第一个字节的指针
2. 通过增加偏移量 offset,找到存放 value 值的内存区域
3. 将该区域转换为 short(两个字节)大小
4. 将 value 复制到该区域,完成 short 类型变量向 bytes 的赋值
来源: