在C#中,ByteBuffer 类似于Java中的 ByteBuffer
using System;using System.Buffers;创建一个 ByteBuffer 实例:// 创建一个长度为10的字节缓冲区var byteBuffer = new byte[10];向 ByteBuffer 写入数据:byteBuffer[0] = 1;byteBuffer[1] = 2;// ...从 ByteBuffer 读取数据:byte firstByte = byteBuffer[0];byte secondByte = byteBuffer[1];// ...使用 ArrayPool<T> 管理内存:// 创建一个字节缓冲区byte[] byteBuffer = ArrayPool<byte>.Shared.Rent(10);try{ // 使用字节缓冲区}finally{ // 释放字节缓冲区 ArrayPool<byte>.Shared.Return(byteBuffer);}使用 BinaryPrimitives 类处理整数和字节之间的转换:using System.Buffers.Binary;int value = 42;byte[] byteBuffer = new byte[sizeof(int)];// 将整数转换为字节BinaryPrimitives.WriteInt32LittleEndian(byteBuffer, value);// 将字节转换回整数int result = BinaryPrimitives.ReadInt32LittleEndian(byteBuffer);使用 BitConverter 类处理浮点数和字节之间的转换:float value = 3.14f;byte[] byteBuffer = BitConverter.GetBytes(value);// 将字节转换回浮点数float result = BitConverter.ToSingle(byteBuffer, 0);使用 MemoryMarshal 类处理结构体和字节之间的转换:using System.Runtime.InteropServices;struct ExampleStruct{ public int A; public float B;}ExampleStruct example = new ExampleStruct { A = 42, B = 3.14f };// 将结构体转换为字节int size = Marshal.SizeOf<ExampleStruct>();byte[] byteBuffer = new byte[size];MemoryMarshal.Write(byteBuffer, ref example);// 将字节转换回结构体ExampleStruct result = MemoryMarshal.Read<ExampleStruct>(byteBuffer);这些示例展示了如何在C#中使用 ByteBuffer(即字节数组)进行数据处理。你可以根据需要调整代码以满足特定场景的需求。


