Post Reply 
Conversion to Binary and IEEE-754 Binary
06-27-2020, 08:37 PM (This post was last modified: 06-29-2020 12:12 PM by Albert Chan.)
Post: #2
RE: Conversion to Binary and IEEE-754 Binary
(06-27-2020 01:35 PM)Eddie W. Shore Wrote:  BASE2 returns a string with precision up to 23 bits.
...
BASE2(π) returns "11.001001000011111101101"

IEEE-754 single precision has 24-bits precision, not 23.
To complement IEEE754(), may be a good idea to match it.

BASE2(π) →                  11.001001 00001111 11011011
IEEE754(π) → 01000000 01001001 00001111 11011011

Quote:IEEE754(2100) returns "0 10001010 100000110100000000000000"
IEEE754(28.725) returns "0 10000011 11100101110011001100110"
IEEE754(-19.5) returns "1 10000011 10011100000000000000000"

All 3 examples were wrong. Using online float-converter, you should get this instead:

IEEE754( 2100 ) = 01000101 00000011 01000000 00000000
IEEE754(28.725) = 01000001 11100101 11001100 11001101
IEEE754(-19.5 ) = 11000001 10011100 00000000 00000000

(06-27-2020 01:35 PM)Eddie W. Shore Wrote:  Sivaraman, Abishalini. "Decimal to IEEE 754 Floating Pont Representation" YouTube Video Published December 4, 2016 https://www.youtube.com/watch?v=8afbTaA-...4_mdWQE84q

Petryk, Steve. "HOW TO: Convert Decimal to IEEE-754 Single-Precision Binary" YouTube Video. Published October 25, 2015. https://www.youtube.com/watch?v=tx-M_rqhuUA

Both videos does not take into account of rounding-to-nearest, for the last bit.
Using Steve example, for x = 45.45

gcc:1> float x = 45.45f       /* suffix f required, otherwise value implicitly converted to double, back to float */
gcc:2> X(*(unsigned*) &x)
0x4235cccd

Repeating bits 0xcccc ... should rounded-up to 0xcccd

---

If conversions were done in binary, there is also a possibility of double-rounding errors.

>>> import gmpy2
>>> x = gmpy2.mpfr('0.50000020861625671')
>>> print format(x,'a')              # rounded 53 bits
0x8.000038p-4

Converting to double precision, x = 0x0.8000037fffffffb8... , got rounded-up.
This happens to be half-way case for single-precision, which got rounded-up again.

>>> b = 2**(53-24)-1
>>> print format(x+b-b,'a')       # rounded 24 bits
0x8.00004p-4

Many online float converters got this one wrong: 0x0.800004
Above converter work very well, and got it right: 0x0.800003

Doing by hand, just scale the number to 24 bits:

0.5000002086162567 = 8388611.4999999997673472 / 2^24

Round-to-nearest, we have 8388611/2^24 = 0x800003p-24 = 0x0.800003

Or, you can try the decimal/binary converter

0.5000002086162567 = 0b0. 10000000 00000000 00000011 01111111...
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Conversion to Binary and IEEE-754 Binary - Albert Chan - 06-27-2020 08:37 PM



User(s) browsing this thread: 1 Guest(s)