Skip to content

Instantly share code, notes, and snippets.

@aniongithub
Created September 9, 2021 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniongithub/50050fc192ac1a16e144bc6de51252db to your computer and use it in GitHub Desktop.
Save aniongithub/50050fc192ac1a16e144bc6de51252db to your computer and use it in GitHub Desktop.
Reconstructing a signed floating point value from its 2's complement fixed point representation in a numpy/cupy friendly way
import numpy as np
from fxpmath import Fxp
N_FRAC = 8
BITS = 32
def twos_comp(val, bits):
# numpy/cupy/kernel friendly version of https://stackoverflow.com/a/9147327
sign_bits = (val & (1 << (bits - 1))) >> (bits - 1)
return np.int32(np.subtract(val, np.multiply(sign_bits, (1 << bits))))
# Get some random values
actual = np.random.ranf(10) - np.random.ranf(10)
# Get fixed point representation
fxp = Fxp(actual, signed = True, n_frac = N_FRAC)
# Get raw values
raw = np.uint32(fxp.raw())
# Calculate two's complement of each of the raw values
twos = twos_comp(raw, BITS)
# Reconstruct the original floating point value
reconstructed = twos / (2 ** N_FRAC)
# How did we do?
print(f"actual: {actual}")
print(f"reconstructed: {reconstructed}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment