博客
关于我
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配置好ssl,但$_SERVER[‘HTTPS‘]取不到值
查看>>
Nginx配置实例-负载均衡实例:平均访问多台服务器
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
nio 中channel和buffer的基本使用
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>