Python 中的反 unsigned char

Inverse unsigned char in Python

我有 C++ 代码:

unsigned char LRC_form(char* cadr)
{
  unsigned char LRC=0;
  unsigned int t=0;
  LRC=0;
  for (t=1;t<0x0D;t=t+2)
  {
    LRC=LRC+ASCII2hex(cadr[t])*16+ASCII2hex(cadr[t+1]);
  }
  return ((~(LRC))+1);
}
int main(int argc, char *argv[])
{
    char *p={":010600000045"};
    cout<<LRC_form(p);
}

其中 ASCII2Hex 是将字符的 ASCII 代码转换为 HEX 的函数。 我必须在 Python 中写同样的内容,所以我这样做:

def LRC_FORM():
    LRC=0
    string_to_send = "010600000045"
    Arr = list(string_to_send)
    #LRC = int(Arr[1])+2
    #print(LRC)
    counter=0
    for i in string_to_send:
        numb = int(i, 16)
        if counter%2 == 0:
            LRC = LRC + numb * 16
        else:
            LRC = LRC + numb
        counter = counter + 1

但是我应该如何实现 (~LRC) + 1 因为 LRC 是一个无符号字符,在我的例子中它是 int,我可以使用一些模块,比如 ctypes 或 struct,但是当我这样做时:

import ctypes
import struct
cchar1=(struct.pack('1B',LRC)) 
cchar2= ctypes.c_char(LRC) 

它没有给我预期的结果。 LRC = 77,虽然我应该得到 LRC = '77',但我得到的是 b'L',所以它不会像 C++ 中的代码那样给出相同的结果。 我怎样才能以正确的方式转换它?

提前致谢!

P.S。 C++ 程序的输出

char *p={":010600000045"};
cout<<LRC_form(p);

正在给予 76 我正在尝试使用 Python 3

编辑 1

return LRC; 

在 C 程序中给出 76。 这与我在 Python 代码中得到的相同。 但是

return ((~(LRC))+1);

给出 180 我不知道我应该怎么做才能在 Python..

中得到相同的结果

编辑 2

ASCII2Hex 函数:

unsigned char ASCII2hex (char ASCII)
{
  if (ASCII<0x40)
    return (ASCII-0x30);
  else
    return (ASCII-0x37);
}
    enter code here

您可以简单地将 AND 与 0xff 强制结果返回到无符号字符范围内:

return ((~LRC)+1) & 0xff

最简单的方法是让 binascii.unhexlify 完成大部分工作。我们只需要向它发送一个 bytes 字符串,而不是文本字符串。

import binascii

def lrc(s):
    # Convert string s to bytes
    b = s.encode('ascii')

    # Interpret hex data in b
    h = binascii.unhexlify(b)

    # Add the byte values
    return sum(h)

# test

s = "010600000045"
print(lrc(s))

输出

76

我们可以使该函数更紧凑,但结果可读性较差:

def lrc(s):
    return sum(binascii.unhexlify(s.encode('ascii')))

我们可以很容易地在Python中做到((~(LRC))+1),但是我们必须要小心,原因有二。首先,Python 没有无符号整数,其次,Python 的整数是无限精度的。但是我们可以通过提供合适的面具来处理这两件事。如果我们想将结果限制为 8 位,我们可以使用 0xff == 255:

的掩码
l = 76
print(l, (0xff & ~l) + 1)

输出

76 180

或者我们可以在反转位之后但在进行掩码之前进行加法:

0xff & (~l + 1)