[英]Python's pack/unpack in .Net
是否有任何 function 等效於 Python 的 struct.pack 和 C# 中的trigger.unpack 允許我像這樣打包和解包值?
查看結構庫。
有一種類似於您在圖片中發布的解包方法
struct.pack(format, v1, v2, ...)
Return a bytes object containing the values v1, v2, … packed according to the format string format. The arguments must match the values required by the format exactly
不,沒有。 您必須使用BinaryWriter
或帶有BitConverter
的MemoryStream
或新的BinaryPrimitives
以及可能由byte[]
支持的Span<>
手動完成(但它更復雜......您必須知道結果寬度開始寫入之前的緩沖區,而MemoryStream
正在自動放大)。
更糟糕的是:.NET 使用多類型數組(每個元素都可以是任何類型的數組),就像unpack
返回的那樣有點不受歡迎,而且性能低下。 您必須使用object[]
,因此您將裝箱每個元素。
現在......手動“序列化”為二進制非常容易(即使比 Python 長得多):
byte command_type = 1;
byte command_class = 5;
byte command_code = 0x14;
int arg0 = 0;
int arg1 = 0;
// We know the message plus the checksum has length 12
var packedMessage2 = new byte[12];
// We use the new Span feature
var span = new Span<byte>(packedMessage2);
// We can directly set the single bytes
span[0] = command_type;
span[1] = command_class;
span[2] = command_code;
// The pack is <, so little endian. Note the use of Slice: first the position (3 or 7), then the length of the data (4 for int)
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(3, 4), arg0);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(7, 4), arg1);
// The checksum
// The sum is modulo 255, because it is a single byte.
// the unchecked is normally useless because it is standard in C#, but we write it to make it clear
var sum = unchecked((byte)packedMessage2.Take(11).Sum(x => x));
// We set the sum
span[11] = sum;
// Without checksum
Console.WriteLine(string.Concat(packedMessage2.Take(11).Select(x => $@"\x{x:x2}")));
// With checksum
Console.WriteLine(string.Concat(packedMessage2.Select(x => $@"\x{x:x2}")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.