unsigned long datapack(void *inBuf, unsigned long len, void *outBuf) { WORD16 *hdr; BYTE *in = (BYTE *)inBuf; BYTE *out = (BYTE *)outBuf; BYTE *pscrc; BYTE *ptr = out; unsigned long i; unsigned long fcs = ~(crc32_le(~0, in, len)); *ptr++ = 0x55; *ptr++ = 0xAA; hdr = (WORD16 *)ptr; ptr += 2; *ptr++ = 0x7e; *ptr++ = 0x7e; for (i = 0; i < len; i++) { switch (in[i]) { case 0x7d: *ptr++ = 0x7d; *ptr++ = 0x5d; break; case 0x7e: *ptr++ = 0x7d; *ptr++ = 0x5e; break; default: *ptr++ = in[i]; break; } } pscrc = (BYTE *)&fcs; for (i = 0; i < 4; i++, pscrc++) { switch (*pscrc) { case 0x7d: *ptr++ = 0x7d; *ptr++ = 0x5d; break; case 0x7e: *ptr++ = 0x7d; *ptr++ = 0x5e; break; default: *ptr++ = *pscrc; break; } } *ptr++ = 0x7e; *ptr++ = 0x7e; *hdr = ptr - out - 4; return ptr - out; } 转化为python程序
时间: 2024-01-13 16:02:56 浏览: 74
#define((volatile unsigned *) ) 讲解
5星 · 资源好评率100%
Here's the Python equivalent of the given C function:
```
import struct
import binascii
def datapack(inBuf, length, outBuf):
inBytes = struct.unpack(str(length)+'B', inBuf)
fcs = binascii.crc32(bytes(inBytes)) ^ 0xffffffff
outBytes = bytearray()
outBytes.append(0x55)
outBytes.append(0xAA)
outBytes.extend(struct.pack('<H', length))
outBytes.append(0x7e)
outBytes.append(0x7e)
for b in inBytes:
if b == 0x7d:
outBytes.extend([0x7d, 0x5d])
elif b == 0x7e:
outBytes.extend([0x7d, 0x5e])
else:
outBytes.append(b)
for i in range(4):
pscrc = (fcs >> (i * 8)) & 0xff
if pscrc == 0x7d:
outBytes.extend([0x7d, 0x5d])
elif pscrc == 0x7e:
outBytes.extend([0x7d, 0x5e])
else:
outBytes.append(pscrc)
outBytes.append(0x7e)
outBytes.append(0x7e)
struct.pack_into('<H', outBytes, 2, len(outBytes) - 6)
outBuf[:len(outBytes)] = outBytes
return len(outBytes)
```
Note: This implementation assumes that `inBuf`, `len`, and `outBuf` are already byte arrays in Python. If they are not, you may need to modify the code accordingly.
阅读全文