博客
关于我
Python 读取16进制byte数据
阅读量:752 次
发布时间:2019-03-23

本文共 2262 字,大约阅读时间需要 7 分钟。

大家好,我是来分享一些关于处理二进制数据存储和转换的问题。最近在做网络编程时,遇到了一个挺棘手的问题:如何在编码和存储过程中避免二进制数据被误解为文本字符,导致进一步转换时出现各种意外情况。下面是具体的解决方法和思路。

问题背景

当我们将二进制数据(比如b'\x00\xff\xfe\x01')转换为字符串类型时,发现有些字符被解释成带有斜杠的文本字符,比如\x00\xff, 这样在将字符串转换回二进制时会产生双斜杠。这种问题尤其显著于文件存储和读取过程中,因为字符串和二进制数据的处理方式不同,容易导致数据损坏。

解决方案一:基于预定义字典的转义处理

针对上述问题,可以写一个自定义的读取函数,通过遍历字符串文件中的转义字符并将它们转换为对应的二进制数据。以下是实现代码:

def readbytetxt(filename):    hex_dict = {        '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,        '8': 8, '9': 9, 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,    }    escape_dict = {        'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 'v': '\v',         "'": "'", '"': '', '\\': '\\',    }    with open(filename, 'r') as f:        for line in iter(f, ''):            line = line.rstrip('\n')            i = 2            length = len(line)            data = b''            while i < length:                if line[i] == '\\' and i+1 < length:                    char = line[i+1]                    if char in escape_dict:                        data += bytes([escape_dict[char]], 'utf-8')                        i += 2                    elif char == 'x' and i+2 < length:                        if line[i+2] in hex_dict and line[i+3] in hex_dict:                            value = hex_dict[line[i+2]] * 16 + hex_dict[line[i+3]]                            data += bytes([value])                            i +=4                        else:                            data += bytes([ord('\\')])  # 不Supported转义                            i +=2                    else:                        data += bytes([ord('\\')])                        i +=2                else:                    data += bytes([ord(line[i])])                    i +=1            yield data

解决方案二:直接处理为数字列表

另一种更为简便的方法是将二进制数据转换为一个数字列表,然后直接存储和读取。代码如下:

data = b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdABCDabcd'int_list = []for byte in data:    int_list.append(int(byte))with open('data.txt', 'w') as f:    f.write(str(int_list))# 读取时:with open('data.txt', 'r') as f:    line = f.readline().strip()    bytes_data = ''.join([bytes([int(x)]) for x in line.split(':')[:1]])    print(bytes_data)

总结

通过以上方法,可以有效避免二进制数据在转换为字符串并存储后出现的格式问题。在实际应用中,可以根据具体需求选择更适合的方案。优化后的代码不仅支持常见的转义字符,还能处理复杂的十六进制编码问题。

转载地址:http://qgbzk.baihongyu.com/

你可能感兴趣的文章
node-static 任意文件读取漏洞复现(CVE-2023-26111)
查看>>
Node.js 8 中的 util.promisify的详解
查看>>
node.js debug在webstrom工具
查看>>
Node.js Event emitter 详解( 示例代码 )
查看>>
Node.js GET、POST 请求是怎样的?
查看>>
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
查看>>
Node.js RESTful API如何使用?
查看>>
node.js url模块
查看>>
Node.js Web 模块的各种用法和常见场景
查看>>
Node.js 之 log4js 完全讲解
查看>>
Node.js 函数是什么样的?
查看>>
Node.js 函数计算如何突破启动瓶颈,优化启动速度
查看>>
Node.js 切近实战(七) 之Excel在线(文件&文件组)
查看>>
node.js 初体验
查看>>
Node.js 历史
查看>>
Node.js 回调函数的原理、使用方法
查看>>
Node.js 在个推的微服务实践:基于容器的一站式命令行工具链
查看>>
Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
查看>>
Node.js 异步模式浅析
查看>>
node.js 怎么新建一个站点端口
查看>>