0 Preface/Foreword
0.1 10进制转其他进制
- bin()
- oct()
- hex()
0.2 其他进制转10进制
- int(, 2)
- int(, 8)
- int(, 16)
1 转换方法
1.1 方法1
先将二进制转成10进制,再将10进制转成16进制
decim = int('00000101', 2)
hexadecim = hex(decim)
print hexadecim
1.2 方法2
import binascii
binary_data = b"\x01\02\03\04\05"
hex_data = binascii.hexlify(binary_data)
hex_data_ascii = binascii.hexlify(binary_data).decode("utf-8")
print hex_data
print hex_data_ascii
解析:
- binary_data:二进制数据
- binascii.hexlify:转成成16进制
- hexlify:返回字节类型
- decode:字符串类型
1.3 2.x和3.x的差异性
源码:
#! /usr/bin/python
#coding:utf-8
import binascii
bin_file="test.bin"
file_mode = "rb"
if __name__ == "__main__":
print("This is main module ..")
fd = open(bin_file, file_mode)
binary_data = fd.read()
print("0x%02x"%binary_data[0])
print (binary_data[0])
print (type(binary_data[0]))
2.x运行结果:
3.x运行结果: