Last active
January 15, 2022 21:05
-
-
Save acdimalev/a574ca9f3e9a341ea165ae45d7ea6973 to your computer and use it in GitHub Desktop.
Decode a Posit-encoded number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# http://web.stanford.edu/class/ee380/Abstracts/170201-slides.pdf | |
from math import inf, log | |
NBITS = 8 | |
ES = 1 | |
def testbit(bits, pos): | |
return bool(bits & 1 << pos) | |
def decode(bits): | |
# zero is zero | |
if bits == 0: | |
return 0.0 | |
# decode inf | |
if bits == 2 ** (NBITS - 1): | |
return inf | |
# decode sign | |
if testbit(bits, NBITS - 1): | |
sign = -1 | |
value = 2 ** NBITS - bits | |
else: | |
sign = 1 | |
value = bits | |
# decode regime | |
if testbit(value, NBITS - 2): | |
for shift in range(NBITS - 1): | |
if shift == NBITS - 2: | |
break | |
if not testbit(value, NBITS - 3 - shift): | |
break | |
regime = shift | |
else: | |
for shift in range(NBITS - 1): | |
if shift == NBITS - 2: | |
break | |
if testbit(value, NBITS - 3 - shift): | |
break | |
regime = -(shift + 1) | |
nfbits = NBITS - 3 - ES | |
exponent_bitmask = 2 ** (NBITS - 3) - 1 | |
fraction_bitmask = 2 ** (NBITS - 3 - ES) - 1 | |
exponent = (value << shift & exponent_bitmask) >> nfbits | |
fraction = value << shift & fraction_bitmask | |
decoded = sign * (2 ** 2 ** ES) ** regime * 2 ** exponent * (1 + fraction / 2 ** nfbits) | |
return decoded |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment