C# equivalent of Python's pack/unpack and sum?

QuatreHuit 1 Reputation point
2021-01-28T12:11:10.837+00:00

Is there any function equivalent to Python's struct.pack and struck.unpack in C# that allows me to pack and unpack values like this?

comman_type = 1
command_class=5
command_code=0x14
arg0=0
arg1=0

packed_message = pack('<bBBii',comman_type,command_class,command_code,arg0,arg1)
cs = sum(unpack('bbbbbbbbbbb',packed_message)
packed_message =   pack('<bBBiib',comman_type,command_class,command_code,arg0,arg1,cs)

I have an array of type char which contains the same data which are at the top on the python code.C#

List<char> tx_buffer2 = new List<char>();

(char message_Type, byte Command_Class, byte command_code,Int32 argument1, Int32 argument2)
Exemple array
('1', 1, 0x22, 1 , 0)

and I want to convert to bytes that respect the format present in pack and unpack function and the sum method

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-01-29T06:08:56.57+00:00

    Hi QuatreHuit-1669,
    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.
    xanatos provided a code example in this thread you can refer to.
    Besides,fdmillion wrote a own class to achieve it in this thead which is useful for you.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments