Converting IEEE Single-precision Real-Number Format to Decimal

Asked 2 years ago, Updated 2 years ago, 14 views

I'm a beginner at computers.
In Python, I would like a program code that converts the IEEE single-precision real-number format to decimal.
(For example,
0011111001100010100011101011100  ⇒ I want to convert to 0.2212499976158142)

Do you have any codes or modules for reference?
Please let me know.

python

2022-09-29 22:48

1 Answers

According to the definition of the IEEE single-precision real-number format, when displayed as a string, the code bit is 1 bit, the exponential part width is 8 bits, and the mantissa part width is 23 bits, so you can calculate as follows:unless the exponent is 00000000 and 111111.(Reference Wikipedia single-precision floating point number)

s='0011111001100010100011101011100'
(-1)**int(s[0:1], 2)*int('1'+s[9:], 2)/2**23*2**(s[1:9], 2)-127)

In reality, it is convenient to convert it into a byte string and use the structure package as described in the comment.

import structure
s='001111100110001010001110101011100'
structure.unpack('f', int(s,2).to_bytes(4, 'little')))[0]

If you use the structure package, you may not be aware of it because it automatically converts to byte columns, but you should also know about endians when dealing directly with memory or binary files or exchanging binary files with other machines.If you use structure.pack to convert it to a byte string on a normal PC, you will see the following:

>>structure.pack ('i', 0b0011111001100010100011101011100)
US>b'\\x8fb>'
>>import binascii
>>binascii.hexlify (struct.pack ('i', 0b0011111001100010100011101011100))
b'5c8f623e'

The 00111110011000101000111110101011100 in this question is Ox3e628f5c, so it is in reverse order.There are two types of methods (byte orders) in which to order things larger than one byte, such as a single-precision real number format, and b'\x5c\x8f\x62\x3e' and the lower order are called "little endians."Place the top row in the b'\x3e\x62\x8f\x5c'' is called the "Big Endian".Intel's CPU uses Little Endian, so it looks like the one above.


2022-09-29 22:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.