首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IEEE-754 Python

IEEE-754 Python
EN

Stack Overflow用户
提问于 2018-07-05 02:14:29
回答 1查看 5K关注 0票数 -1

我如何在python中将带有小数部分的数字转换为IEEE-754的简单精度系统,这样我输入数字并抛出标准符号、指数和尾数?示例输入: 10.27示例输出:0 10000011 01001000101000111101011 Sign-Exponent-Mantissa

这是我尝试解决这个问题的方法。

代码语言:javascript
复制
# Conversion de Decimal a Binario con parte fraccionaria
        def float_bin(num, dig=23):
            # split() separa la parte entera de la parte decimal
            # Despues de separarlas las asignas a dos variables distintas
            ent, dec = str(num).split(".")

            # Convert both whole number and decimal
            # Cambia el tipo de dato de un string a un entero
            ent = int(ent)
            dec = int(dec)
            # Convierte la parte entera a su respectivo forma binaria el "Ob" es removido con el metodo strip
            res = bin(ent).lstrip("0b") + "."
            # Itera el numero de veces dependiendo de numero de posiciones decimales que se buscan
            for x in range(dig):
                # Multiplica la parte fraccionaria por 2 y se separa la parte entera de la parte decimal para repetir el proceso
                ent, dec = str((decimal_conv(dec)) * 2).split(".")

                # Se convierte la parte fraccionaria a un entero de nuevo
                dec = int(dec)

                # Keep adding the integer parts
                # receive to the result variable
                res += ent
            return res


        # Function converts the value passed as
        # parameter to it's decimal representation
        def decimal_conv(num10):
            while num10 > 1:
                num10 /= 10
            return num10


        # Take the user input for
        # the floating point number
        n = input("Ingrese su numero de punto flotante : \n")

        # Take user input for the number of
        # decimal places user want result as
        p = int(input("Ingrese el numero de posiciones decimales para el resultado: \n"))

        print(float_bin(n, dig=p))

        while True:
            ParteSigno = input("Ingresa el signo: ")
            ParteEntera = list(input("Ingresa la parte entera: "))
            ParteDecimal = list(input("Ingresa la parte decimal: "))

            if (ParteSigno == '-'):
                signo = 1
            else:
                signo = 0

            Recorrido = []
            Topepunto = 0
            sacador = 0
            saca = 0
            cont = 0

            if '1' in (ParteEntera):
                Topepunto = len(ParteEntera) - 1
                ExpPar = 127 + Topepunto
                ExpBina = bin(ExpPar)
                ExpobinList = []
                mantisalncom = ParteEntera + ParteDecimal
                mantisalncom.reverse()
                parte = mantisalncom.pop()
                mantisalncom.reverse()
                while len(mantisalncom) < 23:
                    mantisalncom.extend("0")
                for i in ExpBina:
                    ExpobinList.append(i) #El metodo append añade un elemento a la lista
                ExpobinList = (ExpobinList[2:])
                if len(ExpobinList) < 8:
                    ExpobinList.reverse()
                    while len(ExpobinList) <= 8:
                        ExpobinList.extend('0')
                        ExpobinList.reverse()
                else:
                    mantisalncom = ParteEntera + ParteDecimal
                    ParteDecimal.reverse()
                    mantisalncom.reverse()
                    while cont == 0:
                        parte = mantisalncom.pop()
                        if parte == '0' and cont == 0:
                            cont = 0
                        elif parte == '1' and cont == 0:
                            cont = cont + 1
                            mantisalncom.reverse()
                            while len(mantisalncom) < 23:
                                mantisalncom.extend('0')
                        while len(ParteDecimal) > 0:
                            Reco = ParteDecimal.pop()
                            if (Reco == '0' and sacador == 0):
                                Recorrido.extend(Reco)
                                sacador = 0
                            else:
                                sacador = sacador + 1
                                Topepunto = len(Recorrido) + 1
                                Topepunto = Topepunto * (-1)
                                ExpPar = 127 + Topepunto
                                ExpBina = bin(ExpPar)
                                ExpobinList = []
                                for i in ExpBina:
                                    ExpobinList.append(i)
                                ExpobinList = (ExpobinList[2:])
                                if len(ExpobinList) < 8:
                                    ExpobinList.reverse()
                                    while len(ExpobinList) < 8:
                                        ExpobinList.extend('0')
                                        ExpobinList.reverse()

                print("\n\nSigno\t\tExponente\t\t\t\t\t\t\t\tMantisa\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t")
                print("", signo, "", ExpobinList, mantisalncom)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-05 02:37:55

根据您的描述,ucyos answer就是您正在寻找的内容:

代码语言:javascript
复制
def float_to_bin(num):
    bits, = struct.unpack('!I', struct.pack('!f', num))
    return "{:032b}".format(bits)

print(float_to_bin(10.27))
# 01000001001001000101000111101100
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51179116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档