我正在从大型机读取二进制文件,我想将当前以HEX表示的单个进动浮点数转换为在python中转换为其十进制等效值。例如
X'42808000'==>应该转换为128.50十进制.. X'C2808000'==>应转换为-128.50十进制
它们是python中的任何内置函数吗?看起来内部浮动表示不是IEEE格式,而是旧的“S370大型机十六进制格式”。请告诉我你对如何转换相同的想法。谢谢
答案 0 :(得分:0)
从你的问题中不清楚你在哪里说你的数字当前用HEX表示S370十六进制浮点数的格式,不管你是说它们是二进制整数还是字符串值,所以我写了一个函数这将接受任何一个。
try:
basestring
except NameError: # Python 3
basestring = str
def hextofp(hexadecimal):
""" Convert S370 hexadecimal floating-point number to Python
binary floating point value (IEEE 754).
"""
v = int(hexadecimal, 16) if isinstance(hexadecimal, basestring) else hexadecimal
if v: # not special case of "True 0"
sign = -1 if v & 0x80000000 else 1
exponent = ((v & 0x7f000000) >> 24) - 64 # remove bias
fraction = float(v & 0x00ffffff) / 16777216 # divide by 2**24
return sign * (fraction * 16**exponent)
return 0.0
print('{:.2f}'.format(hextofp('42808000'))) # -> 128.50
print('{:.2f}'.format(hextofp(0x42808000))) # -> 128.50
print('{:.2f}'.format(hextofp('C2808000'))) # -> -128.50
print('{:.3f}'.format(hextofp('40600000'))) # -> 0.375
# True 0
print('{:.1f}'.format(hextofp('00000000'))) # -> 0.0
# largest representable number
print('{:.8g}'.format(hextofp('7fffffff'))) # -> 7.2370051e+75
# smallest positive (normalized) number
print('{:.8g}'.format(hextofp('00100000'))) # -> 5.3976053e-79
# misc examples
print('{:.2f}'.format(hextofp('42500000'))) # -> 80.00
print('{:.2f}'.format(hextofp('41100000'))) # -> 1.00
print('{:.3f}'.format(hextofp('C276A000'))) # -> -118.625
print('{:.2f}'.format(hextofp('427b3333'))) # -> 123.20
print('{:.2f}'.format(hextofp('427b7333'))) # -> 123.45