简体   繁体   English

主机S370十六进制浮点数转换为十进制

[英]Conversion of mainframe S370 hexadecimal floating–point to decimal

I am reading a binary file from the mainframe and I would like to convert the single precession floating point numbers which are currently represented in HEX to be converted to its decimal equivalent in python.我正在从大型机读取二进制文件,我想将当前以十六进制表示的单进动浮点数转换为 Python 中的十进制等效值。 For example例如

X'42808000' ==> should be converted to 128.50 in decimal.. X'C2808000' ==> should be converted to -128.50 in decimal X'42808000' ==> 应转换为十进制的 128.50.. X'C2808000' ==> 应转换为十进制的 -128.50

Are they any built in functions in python that does this.它们是否有执行此操作的python 中的任何内置函数。 It looks like the internal floating representations are not in IEEE format but the old "S370 mainframe hexadecimal format".看起来内部浮动表示不是 IEEE 格式,而是旧的“S370 主机十六进制格式”。 Kindly let me know your thoughts on how to convert the same.请让我知道您对如何转换相同的想法。 Thanks谢谢

It's unclear from your question where you say the numbers are currently represented in HEX, for the format of the S370 hexadecimal floating-point numbers, whether you meat that they're binary integer or string values, so I wrote a function that will accept either one.对于 S370 十六进制浮点数的格式,您的问题不清楚您说数字当前以 HEX 表示的位置,无论您认为它们是二进制整数还是字符串值,所以我编写了一个函数,可以接受一。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM