博客
关于我
Python 读取16进制byte数据
阅读量:742 次
发布时间: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/

你可能感兴趣的文章
CentOS5 Linux编译PHP 报 mysql configure failed 错误解决办法
查看>>
python中列表 元组 字典 集合的区别
查看>>
Android DEX加固方案与原理
查看>>
iOS_Runtime3_动态添加方法
查看>>
Leetcode第557题---翻转字符串中的单词
查看>>
Problem G. The Stones Game【取石子博弈 & 思维】
查看>>
Java多线程
查看>>
openssl服务器证书操作
查看>>
我用wxPython搭建GUI量化系统之最小架构的运行
查看>>
selenium+python之切换窗口
查看>>
重载和重写的区别:
查看>>
搭建Vue项目步骤
查看>>
账号转账演示事务
查看>>
SpringBoot找不到@EnableRety注解
查看>>
简易计算器案例
查看>>
在Vue中使用样式——使用内联样式
查看>>
Find Familiar Service Features in Lightning Experience
查看>>
Explore Optimization
查看>>
map[]和map.at()取值之间的区别
查看>>
【SQLI-Lab】靶场搭建
查看>>