Mag Ma

Mag Ma

  • 2.2k
  • 4
  • 2k

C# equivalent of Python's struct.pack and sum?

Jan 28 2021 12:06 PM

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?

import socket
from struct import *
from collections import namedtuple
if __name__ == "__main__":
    # set up params
    command_type = 1
    command_class = 5
    command_code = 0x14
    arg0 = 0
    arg1 = 0
    # encode params
    packed_message = pack('<bBBii', command_type, command_class, command_code, arg0, arg1)
#Resultat : b'\x01\x05\x14\x00\x00\x00\x00\x00\x00\x00\x00'
    # calculate the checksum
    cs = sum(unpack('bbbbbbbbbbb', packed_message))
#Resultat : 26
    # re encode the checksum
    packed_message2 = pack('<bBBiib', command_type, command_class, command_code, arg0, arg1, cs)
#Resultat : b'\x01\x05\x14\x00\x00\x00\x00\x00\x00\x00\x00\x1a'
    # set up the socketprint(packed_message)

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

List<char> tx_buffer2 = new List<char

(char message_Type, byte Command_Class, byte command_code,Int32 argument1, Int32 argument2)  
Example 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

Answers (1)