python数据类型、编码类型的转化

这篇博客介绍了Python中字符串(str)与字节(bytes)之间的互相转换,包括使用encode()和decode()方法,以及通过fromhex()和hex()进行十六进制操作。同时,讲解了整数(int)与字节间的转换,利用`from Crypto.Util.number import *`库的bytes_to_long()和long_to_bytes()函数。此外,还涵盖了二进制、八进制和十六进制的转换,使用int()函数配合基数参数以及bin()、oct()、hex()内置函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

str和bytes

int和bytes

进制转换


str和bytes

>>> Str = "PK\x03\x04"
>>> Str.encode()
b'PK\x03\x04'

>>> Bytes = b'PK\x03\x04'
>>> Bytes.decode()
"PK\x03\x04"
>>> Str = "504B0304"
>>> bytes.fromhex(Str)
b'PK\x03\x04'

>>> Bytes = b'PK\x03\x04'
>>> Bytes.hex()
"504b0304"

举例:以hex形式,读取文件和写入文件

with open('in', 'rb') as f1:
    Str = f1.read().hex()

# Str = "504B0304"
Str1 = ""
for i in range(0, len(Str), 2):
    Str1 += Str[i : i+2]

with open('out', 'wb') as f2:
    f2.write(bytes.fromhex(Str1))

int和bytes

>>> from Crypto.Util.number import *

>>> Bytes = b'flag{}'
>>> bytes_to_long(Bytes)
112615676672893

>>> Int = 112615676672893
>>> long_to_bytes(Int)
b'flag{}'
>>> import libnum

>>> Bytes = b'flag{}'
>>> libnum.s2n(Bytes)
112615676672893

>>> Int = 112615676672893
>>> libnum.n2s(Int)
b'flag{}'

进制转换

>>> 0b1010
10
>>> 0o12
10
>>> 0xa
10

>>> int('0b1010', 2)
10
>>> int('0o12', 8)
10
>>> int('0xa', 16)
10

>>> int('1010', 2)
10
>>> int('12', 8)
10
>>> int('a', 16)
10
>>> bin(10)
'0b1010'
>>> oct(10)
'0o12'
>>> hex(10)
'0xa'

>>> bin(10)[2:]
'1010'
>>> oct(10)[2:]
'12'
>>> hex(10)[2:]
'a'

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值