Hướng dẫn python float hex to binary - python float hex sang nhị phân

Chỉnh sửa lớn về những con số lớnEDIT about big numbers

.

Mã sau đây cho thấy một vấn đề với giải pháp của tôi trong câu trả lời khác của tôi. Lưu ý rằng tôi đã thay đổi tham số của hàm hexf2binf (floathex) từ H thành floathex, để làm cho nó giống như tham số được UNUTBU sử dụng trong hàm floathex_to_binary của anh ấy (floathex)
Note that I changed the parameter of my function hexf2binf(floathex) from h to floathex, to make it the same as the parameter used by unutbu in his function floathex_to_binary(floathex)

from decimal import Decimal,getcontext
getcontext.prec = 500
tinies = [ Decimal(1) / Decimal(2**i) for i in xrange(1,400)]
com = dict((i,tin) for i,tin in enumerate(tinies,1))

def hexf2binf(floathex, tinies = tinies):
    fromh = float.fromhex(floathex)
    print 'fromh = float.fromhex(h)    DONE'
    print 'fromh ==',fromh
    print "str(float.fromhex(floathex)) ==",str(float.fromhex(floathex))

    a,_,p = str(float.fromhex(floathex)).partition('.')
    print 'before the dot ==',a
    print 'after the dot ==',p
    # the following part transforms the float after the dot into a binary after the dot
    bits = []
    pdec = Decimal('.'+p)
    for tin in tinies:
        if pdec-tin==0:
            bits.append('1')
            break
        elif pdec-tin>0:
            bits.append('1')
            pdec -= tin
        else:
            bits.append('0')
    pbin = ''.join(bits) # it's the binary after the dot
    # the float before the dot is easily transformed into a binary
    return '.'.join((bin(int(a)),pbin))



x = x = 123456789012345685803008.0
print '   x = {:f}'.format(x)
h = x.hex()
print '   h = x.hex() ==',h

print '\nENTERING hexf2binf(floathex) with h as argument'
v = hexf2binf(h)
print '\nhexf2binf(x)==',v

kết quả

   x = 123456789012345685803008.000000
   h = x.hex() == 0x1.a249b1f10a06dp+76

ENTERING hexf2binf(floathex) with h as argument
fromh = float.fromhex(h)    DONE
fromh == 1.23456789012e+23
str(float.fromhex(floathex)) == 1.23456789012e+23
before the dot == 1
after the dot == 23456789012e+23

hexf2binf(x)== 0b1.111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111

Vấn đề là do hướng dẫn str(float.fromhex(x)) trong hướng dẫn a,_,p = str(float.fromhex(x)).partition('.') tạo ra, cho một số lượng lớn, một đại diện của float.fromhex (x) với số mũ. Sau đó, các phần trước dấu chấm (a như ante) và sau dấu chấm (p như bài đăng) là sai.float.fromhex(x) with an exponent.
Then THE PARTS BEFORE THE DOT (a as ante) AND AFTER THE DOT (p as post) ARE FALSE.

Sửa lỗi này thật dễ dàng: Thay thế hướng dẫn không chính xác bằng hướng dẫn này:

a,_,p = '{:f}'.format(float.fromhex(x)).partition('.')

.

Mã sau đây cho thấy một vấn đề với giải pháp của tôi trong câu trả lời khác của tôi. Lưu ý rằng tôi đã thay đổi tham số của hàm hexf2binf (floathex) từ H thành floathex, để làm cho nó giống như tham số được UNUTBU sử dụng trong hàm floathex_to_binary của anh ấy (floathex)

kết quả

Vấn đề là do hướng dẫn str(float.fromhex(x)) trong hướng dẫn a,_,p = str(float.fromhex(x)).partition('.') tạo ra, cho một số lượng lớn, một đại diện của float.fromhex (x) với số mũ. Sau đó, các phần trước dấu chấm (a như ante) và sau dấu chấm (p như bài đăng) là sai.
That is shown by the following code:

x1 = 123456789012345685803008.0
print 'x1 == 123456789012345685803008.0'
h2 = x1.hex()
print 'h2 = x1.hex() ==',h2
y1 = float.fromhex(h2)
print 'y1 = float.fromhex(h2) == {:f}'.format(y1)
print

x2 = 123456789012345678901234.64655
print 'x2 == 123456789012345678901234.64655'
h2 = x2.hex()
print 'h2 = x2.hex() ==',h2
y2 = float.fromhex(h2)
print 'y2 = float.fromhex(h2) == {:f}'.format(y2)
print

kết quả

x1 == 123456789012345685803008.0
h2 = x1.hex() == 0x1.a249b1f10a06dp+76
y1 = float.fromhex(h2) == 123456789012345685803008.000000

x2 == 123456789012345678901234.64655
h2 = x2.hex() == 0x1.a249b1f10a06dp+76
y2 = float.fromhex(h2) == 123456789012345685803008.000000

Vấn đề là do hướng dẫn str(float.fromhex(x)) trong hướng dẫn a,_,p = str(float.fromhex(x)).partition('.') tạo ra, cho một số lượng lớn, một đại diện của float.fromhex (x) với số mũ. Sau đó, các phần trước dấu chấm (a như ante) và sau dấu chấm (p như bài đăng) là sai.h2 and h2 are the same because, though different values are assigned to identifiers x1 and x2 in the script, the OBJECTS x1 and x2 are represented with the same approximation in the machine.
The internal representation of 123456789012345685803008.0 is the exact value of 123456789012345685803008.0 and is the internal representation of 123456789012345678901234.64655 but its approximation, hence deduction of h2 and h2 from x1 and x2 gives the same value to h2 and h2.

Sửa lỗi này thật dễ dàng: Thay thế hướng dẫn không chính xác bằng hướng dẫn này:

Nota Bene:

Trên một máy thông thường chạy Python, có 53 bit chính xác có sẵn cho một chiếc phao python, do đó, giá trị được lưu trữ bên trong khi bạn vào số thập phân 0.1 là phân số nhị phân 0.000110011001100110011001100110011001100110011010 HTMLafterdotbinary2float(sbin, com = com) to perform verification on the results yielded by hexf2binf( ). This verification works well when the number passed to hexf2binf( ) isn't big, but because of the internal approximation of big numbers (= having a lot of digits), I wonder if this verification isn't distorted. Indeed, when a big number arrives in the function, it has already been approximated : the digits after the dot have been transformed into a series of zeros;
as it is shown here after:

from decimal import Decimal, getcontext
getcontext().prec = 500
tinies = [ Decimal(1) / Decimal(2**i) for i in xrange(1,400)]
com = dict((i,tin) for i,tin in enumerate(tinies,1))


def afterdotbinary2float(sbin, com = com):
    '''Transforms a binary lying after a dot into a float after a dot'''
    if sbin.startswith('0b.') or sbin.startswith('.'):
        sbin = sbin.split('.')[1]
    if all(c in '01' for c in sbin):
        return sum(int(c)*com[i] for i,c in enumerate(sbin,1))
    else:
        return None



def hexf2binf(floathex, tinies = tinies):
    '''Transforms an hexadecimal float with a dot into a binary float with a dot'''
    a,_,p = '{:.400f}'.format(float.fromhex(floathex)).partition('.')
    # the following part transforms the float after the dot into a binary after the dot
    bits = []
    pdec = Decimal('.'+p)
    for tin in tinies:
        if pdec-tin==0:
            bits.append('1')
            break
        elif pdec-tin>0:
            bits.append('1')
            pdec -= tin
        else:
            bits.append('0')
    pbin = ''.join(bits) # it's the binary after the dot
    # the float before the dot is easily transformed into a binary
    return '.'.join((bin(int(a)),pbin))



for n in (123456789012345685803008.0, 123456789012345678901234.64655, Decimal('123456789012345.2546') ):
    print 'n == {:f}      transformed with its method hex() to:'.format(n)
    nhexed = n.hex()
    print 'nhexed = n.hex() ==',nhexed
    print '\nhexf2binf(nhexed) ==',hexf2binf(nhexed)
    print "\nVerification:\nbefore,_,after = hexf2binf(nhexed).partition('.')"
    before,_,after = hexf2binf(nhexed).partition('.')
    print 'before ==',before,'   after ==',after
    print 'int(before,2) ==',int(before,2)
    print 'afterdotbinary2float(after) ==',afterdotbinary2float(after)
    print '\n---------------------------------------------------------------\n'

kết quả

n == 123456789012345685803008.000000      transformed with its method hex() to:
nhexed = n.hex() == 0x1.a249b1f10a06dp+76

hexf2binf(nhexed) == 0b11010001001001001101100011111000100001010000001101101000000000000000000000000.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Verification:
before,_,after = hexf2binf(nhexed).partition('.')
before == 0b11010001001001001101100011111000100001010000001101101000000000000000000000000    after == 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
int(before,2) == 123456789012345685803008
afterdotbinary2float(after) == 0E-399

---------------------------------------------------------------

n == 123456789012345685803008.000000      transformed with its method hex() to:
nhexed = n.hex() == 0x1.a249b1f10a06dp+76

hexf2binf(nhexed) == 0b11010001001001001101100011111000100001010000001101101000000000000000000000000.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Verification:
before,_,after = hexf2binf(nhexed).partition('.')
before == 0b11010001001001001101100011111000100001010000001101101000000000000000000000000    after == 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
int(before,2) == 123456789012345685803008
afterdotbinary2float(after) == 0E-399

---------------------------------------------------------------

n == 123456789012345.2546      transformed with its method hex() to:

Traceback (most recent call last):
  File "I:\verfitruc.py", line 41, in <module>
    nhexed = n.hex()
AttributeError: 'Decimal' object has no attribute 'hex'

Vấn đề là do hướng dẫn str(float.fromhex(x)) trong hướng dẫn a,_,p = str(float.fromhex(x)).partition('.') tạo ra, cho một số lượng lớn, một đại diện của float.fromhex (x) với số mũ. Sau đó, các phần trước dấu chấm (a như ante) và sau dấu chấm (p như bài đăng) là sai.123456789012345685803008.0 and 123456789012345678901234.64655 makes no difference and no interest.

Sửa lỗi này thật dễ dàng: Thay thế hướng dẫn không chính xác bằng hướng dẫn này:hex() method.

.

Nota Bene:

.

Trên một máy thông thường chạy Python, có 53 bit chính xác có sẵn cho một chiếc phao python, do đó, giá trị được lưu trữ bên trong khi bạn vào số thập phân 0.1 là phân số nhị phân 0.000110011001100110011001100110011001100110011010 HTML

Điều đó có nghĩa là khi một giá trị lớn cho một chiếc phao được viết bằng mã, biểu diễn nội bộ của nó trên thực tế là một xấp xỉ giá trị bằng văn bản. Được hiển thị bằng mã sau:

a,_,p = '{:.400f}'.format(fromh).partition('.')

Các giá trị của H2 và H2 là như nhau bởi vì, mặc dù các giá trị khác nhau được gán cho các định danh X1 và X2 trong tập lệnh, các đối tượng X1 và X2 được biểu diễn bằng cùng một xấp xỉ trong máy. Biểu diễn bên trong của 123456789012345685803008.0 là giá trị chính xác của 123456789012345685803008.0 và là đại diện bên trong của 12345678901p could be truncated, thus giving a binary representation of a slightly different number than the one passed to the function.

Vấn đề này tồn tại khi chúng ta viết một số trong đại diện thập phân trong một kịch bản. Nó không tồn tại khi chúng ta viết một số trực tiếp trong biểu diễn thập lục phân hoặc nhị phân.tinies that contains the Decimal instances corresponding to 1/2 , 1/4 , 1/8 , 1/16 etc

Những gì tôi muốn nhấn mạnh

Bạn có thể chuyển đổi phao thành nhị phân trong Python không?

Python không cung cấp bất kỳ phương pháp sẵn có nào để dễ dàng chuyển đổi số thập phân điểm nổi sang số nhị phân..

Làm thế nào để bạn chuyển đổi từ thập lục phân sang nhị phân?

Hexadecimal để nhị phân chia số hex thành các giá trị riêng lẻ.Chuyển đổi mỗi giá trị hex thành tương đương thập phân của nó.Tiếp theo, chuyển đổi từng chữ số thập phân thành nhị phân, đảm bảo viết bốn chữ số cho mỗi giá trị.Kết hợp tất cả bốn chữ số để tạo một số nhị phân.Split the hex number into individual values. Convert each hex value into its decimal equivalent. Next, convert each decimal digit into binary, making sure to write four digits for each value. Combine all four digits to make one binary number.

Phương pháp điểm nổi nhị phân trong Python là gì?

Số điểm nổi được thể hiện trong phần cứng máy tính dưới dạng phân số cơ sở 2 (nhị phân).Ví dụ: phân số thập phân 0.125 có giá trị 1/10 + 2/100 + 5/1000, và theo cách tương tự, phân số nhị phân 0,001 có giá trị 0/2 + 0/4 + 1/8.base 2 (binary) fractions. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction 0.001 has value 0/2 + 0/4 + 1/8.

Python có thể chuyển đổi hex thành thập phân?

Phương pháp 1: Chuyển đổi thập lục phân sang thập phân trong python bằng int () hàm python int () này có thể được sử dụng để thực hiện nhiệm vụ cụ thể này, thêm một đối sốSố nguyên cùng một lúc.using int() This Python int() function can be used to perform this particular task, adding an argument (16) this function can convert a hexadecimal string number to base sixteen and convert it into an integer at the same time.