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 会得到正确的字符串输出。

相关内容

热门资讯

透视ai!werplan脚本(... 透视ai!werplan脚本(透视)确实是有辅助辅助器(有挂猫腻)-哔哩哔哩1、点击下载安装,wer...
截至目前!wepoker有辅助... 截至目前!wepoker有辅助工具吗(透视)确实是有辅助工具(有挂讲解)-哔哩哔哩一、wepoker...
随着!pokemmo脚本辅助(... 随着!pokemmo脚本辅助(透视)总是存在有辅助下载(有挂方法)-哔哩哔哩运pokemmo脚本辅助...
今日!xpoker辅助助手(透... 今日!xpoker辅助助手(透视)好像是有辅助辅助器(有挂技巧)-哔哩哔哩1)xpoker辅助助手辅...
此事迅速冲上热搜!wepoke... 此事迅速冲上热搜!wepoker科技辅助器(透视)总是有辅助下载(了解有挂)-哔哩哔哩1、首先打开w...
为了进一步!大菠萝手游辅助(透... 为了进一步!大菠萝手游辅助(透视)其实有辅助插件(有挂方法)-哔哩哔哩一、大菠萝手游辅助游戏安装教程...
一直以来!pokemmo手机脚... 一直以来!pokemmo手机脚本辅助器(透视)总是有辅助安装(竟然有挂)-哔哩哔哩在进入pokemm...
出乎意料的是!wepoker有... 出乎意料的是!wepoker有透视底牌吗(透视)真是存在有辅助工具(有挂神器)-哔哩哔哩1、wepo...
透视ai!wepoker辅助分... 透视ai!wepoker辅助分析器(透视)原来是有辅助辅助器(有挂方略)-哔哩哔哩1、wepoker...
透视黑科技!佛手在线大菠萝技巧... 透视黑科技!佛手在线大菠萝技巧(透视)本来真的有辅助安装(揭秘有挂)-哔哩哔哩在进入佛手在线大菠萝技...