写在前面
初学密码学就被各种类型转换的代码实现难住了,当时心情可谓备受打击。所以还是菜鸟的我写篇博客记录一下自己学习到的东西,同时分享给大家。
首先我们得清楚常见的转换类型的形式。
类型 | 实例 |
---|---|
字符串str | “hello world” |
字节数组 | b’hello world’ 或b’\x1c\x01\x11’ |
十六进制字符串hex | 68656c6c6f20776f726c64 |
整型int | 十进制 |
转换
字符串与字节数组转换 在上一篇博客。
字节数组和十六进制字符串转换
1)十六进制字符串转换为字节数组
注:Python3与Python2在这个转换上有所不同
(我这个憨憨曾经备受困扰)
Python2:
Python2中decode方法有hex这个参数,而Python3中没有。
def hex_to_bytelist(hexString):
return [ord(c) for c in hexString.decode('hex')]
Python3:
Python3中新增了bytes这个对象类型, bytes.fromhex这个方法可以从十六进制字符串提取十六进制数并将其转换为字节。
def hex_to_bytelist(hexString):
return bytes.fromhex(hexString)
2)字节数组转换为十六进制字符串
通用方法:
def bytelist_to_hex(bytelist):
return ''.join(hex(x)[2:] if x>15 else'0'+hex(x)[2:] for x in bytelist)
python3方法
def bytelist_to_hex(bytelist):
return bytelist.hex()
3)其他方法
binascii模块(字节–>十六进制字节)
import binascii
string1=b'hello'
string_hex= binascii.b2a_hex(string1)
print(string_hex)
print(bytes.fromhex('68656c6c6f').decode())
output
b'68656c6c6f'
hello
字符串和十六进制字符串的转换
1)字符串转换为十六进制字符串
Python2:
def str_to_hex(string):
return string.encode('hex')
Python3: ①利用上面已经定义的函数进行转换 曲线救国
②引入codecs模块,利用codecs模块中的编码方法。
思路str—>字节—>十六进制字符串。(如下代码)
def str_to_hex(string):
import codecs
byte1=string.encode('utf-8')
return (codecs.encode(byte1,'hex')).decode('utf-8')
2)十六进制字符串转换为字符串
Python2:
def hex_to_str(hexString):
return hexString.decode('hex')
Python3:
def hex_to_str(hexString):
return (bytes.fromhex(hex_string)).decode('utf-8')
整型和字节的转换
1)将字节转换为整型
int.from_bytes(bytes, byteorder, *, signed=False)
功能:res = int.from_bytes(x)的含义是把bytes类型的变量x,转化为十进制整数,并存入res中。
原理:bytes—>二进制数–>十进制数
参数:int.from_bytes(bytes, byteorder, *, signed=False)
bytes是十六进制字节
byteorder有big和little,big是顺序,little是倒序 (十六进制字节的顺序)
sighed=true代表带正负号(二进制),false代表不带符号
返回十进制数
2)将整型转换为字节
int.to_bytes()
功能:是int.from_bytes的逆过程,把十进制整数,转换为bytes类型的格式。
以上。