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

  1. str和bytes
  2. int和bytes
  3. 进制和ascii

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('1.txt', 'rb') as f:
    str_ = f.read().hex()

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

with open('2.txt', 'wb') as f:
    f.write(bytes.fromhex(str_1))

int和bytes

>>> bytes_ = b"flag{}"
>>> int.from_bytes(bytes_, 'big')
112615676672893

>>> int_ = 112615676672893
>>> int_.to_bytes(10, 'big')
b'\x00\x00\x00\x00flag{}'
>>> from Crypto.Util.number import *
 
>>> bytes_ = b"flag{}"
>>> bytes_to_long(bytes_)
112615676672893

>>> int_ = 112615676672893
>>> long_to_bytes(int_)
b'flag{}'
>>> bytes_ = b"flag{}"
>>> list(bytes_)
[102, 108, 97, 103, 123, 125]

>>> list_ = [102, 108, 97, 103, 123, 125]
>>> bytes(list_)
b'flag{}'

进制和ascii

>>> 0b1100001
97
>>> 0o12
97
>>> 0xa
97

>>> int("0b1100001", 2)
97
>>> int("0o141", 8)
97
>>> int("0x61", 16)
97

>>> int("1100001", 2)
97
>>> int("141", 8)
97
>>> int("61", 16)
97
>>> bin(97)
'0b1100001'
>>> oct(97)
'0o141'
>>> hex(97)
'0x61'

>>> bin(97)[2:]
'1100001'
>>> oct(97)[2:]
'141'
>>> hex(97)[2:]
'61'
>>> ord("a")
97

>>> chr(97)
'a'

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件至 skatexu@qq.com

文章标题:python数据类型、编码类型的转化

字数:412

本文作者:skateXu

发布时间:2023-10-12, 20:45:12

最后更新:2023-10-12, 22:41:18

原始链接:http://example.com/2023/10/12/python%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E3%80%81%E7%BC%96%E7%A0%81%E7%B1%BB%E5%9E%8B%E7%9A%84%E8%BD%AC%E5%8C%96/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。