将使用char类型的C ++代码翻译为Python

时间:2014-04-10 11:24:21

标签: python c++

这段代码在python中会怎么样? nrComm1->SendChar可以替换为serial.write(A_CHAR)

void prepare()
{
    char temp[50];
    sprintf(temp,"%04XT2000A", 76);

    send(temp);
}

void send(char *TX_String)
{
    unsigned char checksum = 0x02;  

    nrComm1->SendChar(0x02);
    while(*TX_String)
    {
        nrComm1->SendChar(*TX_String);
        checksum ^= *TX_String++;
    }
    nrComm1->SendChar(0x03);
    checksum ^= 0x03;                            

    nrComm1->SendChar(checksum);
}

1 个答案:

答案 0 :(得分:2)

它看起来像这样(不是一个有效的例子,只是为了让你开始):

更新:提供了如何使示例正常工作的提示......

def prepare():
    temp = "%04XT2000A" % 76
    send(temp)


def send(tx_string):
    checksum = 0x02
    serial.write(checksum)

    # hint: int conversion will not work since tx_string is a
    # string representation of a hex value, add conversion code for this
    while(tx_string):
        serial.write(int(tx_string[0]))
        checksum = checksum ** int(tx_string[0])
        tx_string = tx_string[1:]

    serial.write(0x03)
    checksum = checksum ** 0x03
    serial.write(checksum)