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的赋值

相关文章:

  • 2021-10-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
猜你喜欢
  • 2021-09-27
  • 2022-12-23
  • 2021-09-07
  • 2022-12-23
  • 2022-03-08
  • 2022-12-23
  • 2021-09-24
相关资源
相似解决方案