Python Forum

Full Version: help with converting C# function to Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hello ,
I have this C# function that work as a checksum
public static byte gen(byte[] p)
         {
            byte lcs = 0;
            foreach (byte b in p)
            {
                lcs += b;

            }

            lcs = (byte)(0 - lcs);
            return lcs;

        }
how can I change it to work in python?

Example I have this value in DEC:
48,51,50,51,3
the sum is 203 (which is CB in Hex)
so I need it to return 100-CB = 35
then break the 35 into 2 numbers: 3,5 -->so it will send byte 51,53

Thanks ,
I've got this
>>> d = bytes([48,51,50,51,3])
>>> str(256 - sum(d)).encode('ascii')
b'53'
#!/usr/bin/python3
def gen(p):
    lcs = 0
    for b in p:
        lcs += b
        lcs %= 256

    lcs = 256 - lcs
    return lcs


rc1 = gen([48,51,50,51,3])
print("rc1=", rc1)

rc2 = "%x" % rc1
print("rc2=", rc2)

d1 = ord(rc2[0])
d2 = ord(rc2[1])
print("d  =", d1, d2)
rc1= 53
rc2= 35
d = 51 53
Thanks ,
it working

Now I need to see how to combine it insdie the main code :

this is what I did :

import serial                          # import the module 

def gen(p):                            #The CheckSum Function
    lcs = 0
    for b in p:
        lcs += b
        lcs %= 256
 
    lcs = 256 - lcs
    return lcs
 


COM_PortName = ('/dev/ttyUSB0')


COM_Port = serial.Serial(COM_PortName) # open the COM port
print('\n   ',COM_PortName,'Opened')

COM_Port.baudrate = 4800               # set Baud rate 
COM_Port.bytesize = 8                  # Number of data bits = 8
COM_Port.parity   = 'N'                # No parity
COM_Port.stopbits = 1                  # Number of Stop bits = 1


COM_Port.setDTR(0) #DTR=0,~DTR=1 so DE = 1,Transmit mode enabled
COM_Port.setRTS(0) #RTS=0,~RTS=1 (In FT232 RTS and DTR pins are inverted)
      
 

#this is an example of what need to be send : 
#data = bytearray(b'\x02\x30\x33\x32\x33\x03\x33\x35') # Convert Character to byte array 

# 
SOF = bytearray(b'\x02')
SignAdd = bytearray(b'\x30\x33')
MSG = input('\n Enter Number - ')
EOF = bytearray(b'\x03')
 
rc1 = gen([SignAdd,MSG,EOF])
print("rc1=", rc1)
 
rc2 = "%x" % rc1
print("rc2=", rc2)
 
d1 = ord(rc2[0])
d2 = ord(rc2[1])
print("d  =", d1, d2)

NoOfBytes  = COM_Port.write(SOF)            # Write data to serial port
NoOfBytes  = COM_Port.write(SignAdd) 
NoOfBytes  = COM_Port.write(MSG) 
NoOfBytes  = COM_Port.write(d1,d2) 

print('\n message was - ',MSG)
     
COM_Port.close()                       # Close the Serial port

dummy = input()                        # press any key to close 
in the input I only put numbers 0-99
but I get error from the gen function:
TypeError: unsupported operand type(s) for +=: 'int' and 'bytearray'
what is the mistake?

Thanks ,

if the answer could be with en explain , So I will learn it will be great :-)
I do not have a serial port,
so I write the output to a binary file.
I hope, this helps you.

!/usr/bin/python3
def gen(bytes):
    lcs = 0
    for b in bytes:
        lcs += b
        lcs %= 256

    lcs = 256 - lcs
    return lcs

COM_PortName = 'serial.txt'
COM_Port     = open(COM_PortName, "wb")

SOF     = b'\x02'
SignAdd = b'\x30\x33'
MSG     = input('\n Enter Number - ').encode()
EOF     = b'\x03'

rc1 = gen(SignAdd + MSG + EOF)
rc2 = "%02x" % rc1

NoOfBytes  = COM_Port.write(SOF)
NoOfBytes  = COM_Port.write(SignAdd)
NoOfBytes  = COM_Port.write(MSG)
NoOfBytes  = COM_Port.write(rc2.encode())
print('\n message was - ',MSG)
COM_Port.close()
#done
Quote:if the answer could be with en explain , So I will learn it will be great :-)
We don't know what p means when it enters gen(). Can you print(repr(p)) at the beginning of the gen() function and post the output here?
not working
this is the code now:
import serial                          # import the module 
	
def banner_bottom():
	print('   +-------------------------------------------+')
	print('   |          Press Any Key to Exit            |')
	print('   +-------------------------------------------+')

def gen(p):
    print(repr(p))
    lcs = 0
    for b in p:
        lcs += b
        lcs %= 256
 
    lcs = 256 - lcs
    return lcs
 

COM_PortName = ('/dev/ttyUSB0')

COM_Port = serial.Serial(COM_PortName) # open the COM port
print('\n   ',COM_PortName,'Opened')

COM_Port.baudrate = 4800               # set Baud rate 
COM_Port.bytesize = 8                  # Number of data bits = 8
COM_Port.parity   = 'N'                # No parity
COM_Port.stopbits = 1                  # Number of Stop bits = 1


COM_Port.setDTR(0) #DTR=0,~DTR=1 so DE = 1,Transmit mode enabled
COM_Port.setRTS(0) #RTS=0,~RTS=1 (In FT232 RTS and DTR pins are inverted)


#data = bytearray(b'\x02\x30\x33\x32\x33\x03\x33\x35') # Convert Character to byte array 
SOF = b'\x02'
EOF = b'\x03'
SignAdd = b'\x30\x33'
MSG = input('\n Enter Number - ').encode()

ToCs=[SignAdd + MSG + EOF]
rc1 = gen(ToCs)
print("rc1=", rc1)
 
rc2 = "%x" % rc1
print("rc2=", rc2)
 
d1 = ord(rc2[0])
d2 = ord(rc2[1])
print("d  =", d1, d2)

NoOfBytes  = COM_Port.write(SOF)            # Write data to serial port
NoOfBytes  = COM_Port.write(SignAdd) 
NoOfBytes  = COM_Port.write(MSG) 
NoOfBytes  = COM_Port.write(rc2.encode()) 

print('\n message was - ',MSG)
      
COM_Port.close()                       # Close the Serial port

banner_bottom()                        # Display the bottom banner
dummy = input()                        # press any key to close 
and this is the erro I'm getting
 Enter Number - 23
[b'0323\x03']
Traceback (most recent call last):
  File "/home/pi/mu_code/MyProgram/RS485_Write.py", line 59, in <module>
    rc1 = gen(ToCs)
  File "/home/pi/mu_code/MyProgram/RS485_Write.py", line 23, in gen
    lcs += b
TypeError: unsupported operand type(s) for +=: 'int' and 'bytes'
maybe it will be easy if I read the number from a file?

I have a text file with "23" as it's content :
MSG = open('/home/pi/Documents/test.txt' , 'r') 
but now I get this error:
Traceback (most recent call last):
  File "/home/pi/mu_code/MyProgram/RS485_Write.py", line 59, in <module>
    ToCs=[SignAdd + MSG + EOF]
TypeError: can't concat bytes to _io.TextIOWrapper
Your output shows that p is a list with one element instead of a bytes instance. You neeed co call gen(ToCs[0])
yes , now it's working !
so what is the differant?
if ToCs have only 1 element , why do I need to tell the function to read just ToCs[0]?

Thanks
Quote:why do I need to tell the function to read just ToCs[0]?
This example explains the issue. Take the time to understand it
>>> p = [b'spam']
>>> for x in p:
...     print(x)
... 
b'spam'
>>> p = b'spam'
>>> for x in p:
...     print(x)
... 
115
112
97
109
>>>
Pages: 1 2