Python struct模块和bytes,str,decode,encode

本文介绍了Python中的struct模块,包括encode和decode、bytes与str类型的区别、bytes()函数,重点讲解了struct模块的pack()和unpack()函数,用于处理二进制数据和转换C结构体。
摘要由CSDN通过智能技术生成

概述

0)encode, decode

print(type(‘struct模块’.encode(‘utf-8’)))
print(type(‘struct模块’.encode(‘gbk’)))
print(type(‘struct模块’.encode(‘gb2312’)))
print(type(str(‘struct模块’.encode(‘gb2312’))))
print(type(‘struct模块’.encode(‘gb2312’).decode(‘gb2312’)))
print(type(‘struct模块’))
<class ‘bytes’>
<class ‘bytes’>
<class ‘bytes’>
<class ‘str’>
<class ‘str’>
<class ‘str’>
aa.encode(a)表示此字符串编码为此码a,
aa.decode(b)表示此字符串采用码b进行解码,b必须是aa的码。
print(type(‘struct模块’.encode(‘gb2312’).decode(‘utf-8’)))是错误的

在这里插入图片描述

1)bytes、str

bytes是Python3.x新加的数据类型(在Python2.x中被合并在str)中

在这里插入图片描述

2)bytes()

bytes()是Python3的一个内置函数

在这里插入图片描述
准确的讲,Python没有提供专门处理字节的数据类型
但由于b’str_obj’可以表示bytes_obj
所以,字节数组 <=> 二进制str

C语言中,我们可以很方便地用struct、union来处理字节,以及字节和int、float的转换

你可以使用位运算把其他数据类型转换为字节类型。
s1 = b’\xf1\xff’
print(int.from_bytes(s1, byteorder=‘big’, signed

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值