bytearray中包含空字符的PyByteArray_AsString的解决方案
创始人
2025-01-12 21:00:20
0

由于 PyByteArray_AsString 只适用于不含空字符的 bytearray,如果在 bytearray 中含有空字符,转换为字符串会出现错误。但是可以通过使用 PyUnicode_AsUTF8AndSize 和 PyBytes_FromStringAndSize 函数来解决该问题。

以下是代码示例:

import ctypes
import sys

PY3 = sys.version_info[0] == 3

if PY3:
    get_buffer = memoryview
    unicode_type = str
    xrange = range
else:
    def get_buffer(m):
        return m

    unicode_type = unicode


def bytearray_as_string(bytearray_obj):
    buf = get_buffer(bytearray_obj)
    size = len(bytearray_obj)

    # Find the index of the first null character
    null_idx = -1
    for i in xrange(size):
        if buf[i] == b'\0':
            null_idx = i
            break

    if null_idx == -1:
        # No null characters found, use PyByteArray_AsString
        return ctypes.c_char_p(buf).value
    else:
        # Convert to PyUnicodeObject first
        # Use PyUnicode_AsUTF8AndSize to convert to UTF-8 encoded bytes
        # Use PyBytes_FromStringAndSize to convert the bytes to string
        unicode_obj = PyUnicode_DecodeUTF8(ctypes.c_char_p(buf).value, size, NULL)
        return PyBytes_AsString(PyUnicode_AsUTF8String(unicode_obj))


# Usage example
bytearray_obj = b'hello\0world'
print(bytearray_as_string(bytearray_obj))

使用 bytearray_as_string 函数来转换带空字符的 bytearray 会得到正确的字符串输出。

相关内容

热门资讯

现有关情况通报如下!aapok... 现有关情况通报如下!aapoker真的假的(透视)hhpoker怎么开透视-本来是有挂(哔哩哔哩)1...
据悉!智星德州有脚本吗(透视)... 据悉!智星德州有脚本吗(透视)智星德州可以透视吗-其实存在有挂(哔哩哔哩)智星德州可以透视吗脚本下载...
长期以来!wepoker养号规... 长期以来!wepoker养号规律(透视)wepoker透视辅助-都是存在有挂(哔哩哔哩)1、上手简单...
透视规律!微扑克微乐辅助(透视... 透视规律!微扑克微乐辅助(透视)wpk软件是真的吗-一直真的是有挂(哔哩哔哩)1、微扑克微乐辅助模拟...
透视规律!德普之星私人局辅助器... 透视规律!德普之星私人局辅助器(透视)德普之星app安卓版破解版-确实有挂(哔哩哔哩)德普之星app...
透视线上!aapoker公共底... 透视线上!aapoker公共底牌(透视)hhpoker是正品吗-切实是真的挂(哔哩哔哩)1、首先打开...
连日来!hhpoker万能辅助... 连日来!hhpoker万能辅助器(透视)德州局hhpoker-竟然是有挂(哔哩哔哩)1、hhpoke...
经调查!aapoker怎么设置... 经调查!aapoker怎么设置提高好牌几率(透视)hhpoker有辅助吗-一贯存在有挂(哔哩哔哩)a...
透视辅助!hhpoker透视码... 透视辅助!hhpoker透视码(透视)hhpoker辅助靠谱吗-原来真的有挂(哔哩哔哩)1、金币登录...
透视线上!德州局hhpoker... 透视线上!德州局hhpoker(透视)hhpoker真的有透视吗-确实真的是有挂(哔哩哔哩)1、用户...