Home > other >  C function to Python
C function to Python

Time:10-11

Can someone help to make Python version of function. Thanks

unsigned char asap_xor(unsigned char *msg, int len) {
    unsigned char xor_val = 0;
    int i;
    xor_val = msg[0];
    for (i = 1; i < len; i  ) {
        xor_val ^= msg[i];
    }
    xor_val = 13 ^ xor_val;
    xor_val = xor_val | 0x40;
    return (xor_val);
}

Python version thanks to Olvin Roght

from functools import reduce
from operator import xor
from itertools import islice
def asap_xor(msg, length=0):
    return 13 ^ reduce(xor, islice(msg, length) if length else msg) | 0x40

CodePudding user response:

Not sure what version of python you are on, but for python 3.5 or so, this should work:

def asap_xor(msg):        
    xor_val = msg[0]

    for m in msg[1:]:
        xor_val ^= m

    xor_val = (13 ^ xor_val)
    xor_val = (xor_val | 0x40)

    return xor_val

print(asap_xor("test".encode('utf8')))
print(asap_xor(b"test"))

CodePudding user response:

First compile the c code:

gcc py_test.c -shared -fPIC -o py_test_libc.so

Then import the ctypes module in Python, and use the cdll class:

from ctypes import cdll

The complete python code is as follows:

from ctypes import cdll
c_function = cdll.LoadLibrary("./py_test_libc.so")

res = c_function.py_test(123)
# py_test is the name of the C function
# 123 is a parameter

print(res)
  • Related