在 Python 3 中将 '\x00' 转换为 ASCII
Convert '\x00' to ASCII in Python 3
我目前有以下操作:
a = 'cat\x00 '
格式为unicode(默认Python3字符串格式)。我希望将其转换为 ASCII。到目前为止我试过这个:
a = bytes(a, 'ascii')
print(a)
OUT: b'cat\x00 '
使用 byes 命令将 'a' 转换为原始字符串,而不执行 '\x' 转义字符。执行十六进制转换后,有没有办法将 'a' 转换为 ASCII?
我需要 'a' 的值用于 ctypes:
ct.c_char_p(a)
只需传递 b'cat'
或 'cat'.encode()
。两者都会将以空字符结尾的字节字符串传递给 c_char_p
ctypes 参数。您不需要自己添加 null。
在 some.dll
中调用 void func(const char* s)
的示例:
from ctypes import *
dll = CDLL('some.dll')
dll.func.argtypes = [c_char_p]
dll.func.restype = None
dll.func(b'cat')
dll.func('cat'.encode())
ct.c_char_p(a.encode('UTF-8'))
我目前有以下操作:
a = 'cat\x00 '
格式为unicode(默认Python3字符串格式)。我希望将其转换为 ASCII。到目前为止我试过这个:
a = bytes(a, 'ascii')
print(a)
OUT: b'cat\x00 '
使用 byes 命令将 'a' 转换为原始字符串,而不执行 '\x' 转义字符。执行十六进制转换后,有没有办法将 'a' 转换为 ASCII?
我需要 'a' 的值用于 ctypes:
ct.c_char_p(a)
只需传递 b'cat'
或 'cat'.encode()
。两者都会将以空字符结尾的字节字符串传递给 c_char_p
ctypes 参数。您不需要自己添加 null。
在 some.dll
中调用 void func(const char* s)
的示例:
from ctypes import *
dll = CDLL('some.dll')
dll.func.argtypes = [c_char_p]
dll.func.restype = None
dll.func(b'cat')
dll.func('cat'.encode())
ct.c_char_p(a.encode('UTF-8'))