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

相关内容

热门资讯

透视教你"wepok... 透视教你"wepoker辅助器是真的吗"本来真的是有辅助方法(哔哩哔哩)进入游戏-大厅左侧-新手福利...
透视总结"aapok... 透视总结"aapoker辅助插件工具"好像有辅助插件(哔哩哔哩)1、上手简单,内置详细流程视频教学,...
透视透视"aapok... 透视透视"aapoker怎么设置抽水"总是真的是有辅助神器(哔哩哔哩)1、aapoker怎么设置抽水...
透视辅助"poker... 透视辅助"poker world辅助"真是是真的辅助挂(哔哩哔哩)1、这是跨平台的poker wor...
透视有挂"德州辅助工... 透视有挂"德州辅助工具到底怎么样"果然有辅助挂(哔哩哔哩)1)德州辅助工具到底怎么样免费钻石:进一步...
透视解谜"wpk俱乐... 透视解谜"wpk俱乐部怎么作必弊"一直是真的辅助软件(哔哩哔哩)1、wpk俱乐部怎么作必弊破解器简单...
透视教你"wepok... 透视教你"wepoker有辅助工具吗"一贯存在有辅助工具(哔哩哔哩)1、打开软件启动之后找到中间准星...
透视推荐"poker... 透视推荐"pokerworld修改器"原来真的是有辅助器(哔哩哔哩)1、下载好pokerworld修...
透视解迷"pokem... 透视解迷"pokemmo辅助官网"本来有辅助攻略(哔哩哔哩)1、每一步都需要思考,不同水平的挑战会更...
透视揭露"wepok... 透视揭露"wepoker可以开透视吗"一直存在有辅助神器(哔哩哔哩)1、该软件可以轻松地帮助玩家将w...