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

相关内容

热门资讯

黑科技科技(wepoke智能a... 黑科技科技(wepoke智能ai)wepower使用说明书(wepOkE)素来是真的有挂(确实有挂)...
黑科技模拟器(wepoke智能... WePoker透视辅助工具核心要点解析‌,黑科技模拟器(wepoke智能ai)wepoke是机器发牌...
黑科技脚本(wepokeai代... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏中打牌都...
黑科技辅助挂(wepoke真的... 黑科技辅助挂(wepoke真的有挂)wepoke 软件(wEPOKE)固有真的有挂(有挂猫腻)-哔哩...
黑科技辅助挂(wepoke黑科... 黑科技辅助挂(wepoke黑科技)wepoke软件透明挂演示(wEpOke)一直真的有挂(真的有挂)...
黑科技app(wepoke真的... 此外,数据分析德州()辅助神器app还具备辅助透视行为开挂功能,通过对客户透明挂的深入研究,你可以了...
黑科技智能ai(wepoke辅... 黑科技智能ai(wepoke辅助插件)wepoke软件透明(WEPOke)先前是有挂(果真有挂)-哔...
黑科技模拟器(wepoke透明... 黑科技模拟器(wepoke透明黑科技)wepoke德州扑克用ai代打(WEPOKE)最初存在有挂(有...
黑科技插件(wepoke辅助插... 黑科技插件(wepoke辅助插件)wepoke软件透明(WEPOke)从来是真的有挂(有挂解惑)-哔...
黑科技美元局(wepoke智能... 黑科技美元局(wepoke智能ai)wepoke辅助真的假的(wepoKE)原先真的有挂(竟然有挂)...