博客
关于我
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/

你可能感兴趣的文章
Nginx 集成Zipkin服务链路追踪
查看>>
nginx 集群配置方式 静态文件处理
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx、HAProxy、LVS
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>
Nginx从入门到精通
查看>>
Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)
查看>>
Nginx代理初探
查看>>
nginx代理地图服务--离线部署地图服务(地图数据篇.4)
查看>>