Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent of python's struct.pack

Is there a library for C# that allows similar functionality to python's struct from the standard library?

One can emulate the struct library quite closely with real aligned structs. But I didn't find yet any way to directly control the endianess in C#'s structs (the C#'s structs seems to be geared more towards COM interop, and less toward general purpose binary packing).

like image 902
Elazar Leibovich Avatar asked Jan 30 '26 03:01

Elazar Leibovich


1 Answers

The closest equivalent would probably be to use BinaryWriter writing into a MemoryStream, or BitConverter for a one-off conversion of a single value into a byte array.

If you want to control the endianness of that, you can use my EndianBinaryWriter/EndianBitConverter from MiscUtil. One extra feature of my EndianBitConverter is that you can convert into a specific portion of an existing array, which would help you if you wanted to port struct.pack yourself.

like image 89
Jon Skeet Avatar answered Jan 31 '26 16:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!