BinaryPrimitives.WriteXXXBigEndian
Program.cs
public class Program
{
private static readonly int HEADER_SIZE = 5;
private const ushort PACKET_ID_ECHO = 1;
public static void Main(string[] args)
{
byte[] bytes = new byte[4];
BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan<byte>(0, 2), 7);
BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan<byte>(2, 2), 300);
Console.WriteLine("{0}, {1}", bytes[0], bytes[1]);
Console.WriteLine("{0}, {1}", bytes[2], bytes[3]);
string data = @"{""a"":""hello""}";
byte[] body = Encoding.UTF8.GetBytes(data);
ushort totalSize = (ushort) (HEADER_SIZE + body.Length);
bytes = new byte[totalSize];
BinaryPrimitives.WriteUInt16BigEndian(new Span<byte>(bytes, 0, 2), totalSize);
BinaryPrimitives.WriteUInt16BigEndian(new Span<byte>(bytes, 2, 2), PACKET_ID_ECHO);
Buffer.BlockCopy(new byte[1], 0, bytes, 4, 1); // byte
Buffer.BlockCopy(body, 0, bytes, HEADER_SIZE, body.Length);
Console.WriteLine("{0}, {1}", bytes[0], bytes[1]);
Console.WriteLine("{0}, {1}", bytes[2], bytes[3]);
}
}
references
https://copyprogramming.com/howto/c-int-to-byte
https://learn.microsoft.com/ko-kr/dotnet/api/system.buffers.binary.binaryprimitives?view=net-8.0
https://stackoverflow.com/questions/59774345/correct-way-to-convert-between-basic-types-and-raw-bytes
'c# .net' 카테고리의 다른 글
csharp .net WebSocket Server (0) | 2025.02.23 |
---|---|
c# .net Socket NetworkStream (1) | 2024.11.10 |
c# SocketAsyncEvent Server (0) | 2024.11.09 |
csharp .net CsvHelper (0) | 2024.10.12 |
c# .net Leaky Bucket (0) | 2024.07.20 |