float型/int型数据和底层2进制表示互转
版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc
引言:
因为需要打印float型/int型二进制表示
这里封装了几个函数,方便日后使用。
struct_utils.py
import struct
def type2bin(num, fmt):
ll = [bin(ord(c)) for c in struct.pack(fmt, num)]
res = []
for item in ll:
res.append(item.replace('0b', '').rjust(8, '0'))
return ''.join(res)
def bin2type(bits, fmt):
return struct.unpack(fmt, struct.pack(fmt, int(bits, 2)))[0]
def float2bin(num):
return type2bin(num, '>f')
def bin2float(bits):
return bin2type(bits, '>f')
def int2bin(num):
return type2bin(num, '>i')
def bin2int(bits):
return bin2type(bits, '>i')
def long2bin(num):
return type2bin(num, '>q')
def bin2long(bits):
return bin2type(bits, '>q')
if __name__ == '__main__':
res = float2bin(5.5)
print res
res = bin2float(res)
print res
print '-----------------'
res = int2bin(345)
print res
res = bin2int(res)
print res
print '-----------------'
res = long2bin(345)
print res
res = bin2long(res)
print res