0

这是我的第一个 cython (pyx) 模块。我怎样才能让它更快?具体来说,我正在最后一行寻求帮助。它可以编译并运行,但我担心它会被转换为 Py* 对象,这可能会快得多。

另外,如果您发现任何明显的错误,请告诉我!

ctypedef unsigned short UInt8

DEF BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

def encode_16_bytes(char *thebytes):
    cdef UInt8 *b      # the bytes cast to an array of UInt8
    cdef int i         # used to assign a value to the buffer
    cdef int j         # used to count up through the bytes
    cdef char buf[23]  # the resulting buffer of characters

    # initialize variables
    for i in range(23): # set buf array to zeros
        buf[i] = '\0'
    b = <UInt8 *>thebytes
    i = 0
    j = 1

    i += 1
    buf[i] = BASE64[(b[0] >> 6) & 0x3F]
    i += 1
    buf[i] = BASE64[b[0] & 0x3F]

    # iterate through the bytes 4 words at a time, setting each byte to its
    # mapped BASE64 counterpart
    while j < 16:
        i += 1
        buf[i] = BASE64[(b[j] >> 2) & 0x3F]
        i += 1
        buf[i] = BASE64[((b[j] << 4) | (b[j + 1] >> 4)) & 0x3F]
        i += 1
        buf[i] = BASE64[((b[j + 1] << 2) | (b[j + 2] >> 6)) & 0x3F]
        i += 1
        buf[i] = BASE64[b[j + 2] & 0x3F]
        j += 3

    # join up the characters into a string
    return "".join([chr(buf[i]) for i in range(23)])

谢谢!

4

1 回答 1

1

您可以通过将 "".join(...) 替换为以下内容,从 C 字符缓冲区中创建 Python 字节字符串:

bytes_string = chr[:23]

或更一般地说:

bytes_string = chr[:buffer_length]

请参阅此处以获取参考和更多示例。

于 2012-09-20T17:10:58.183 回答