Created
March 27, 2016 18:11
-
-
Save mitchellrj/58c13b5c8e4052c6e4ef to your computer and use it in GitHub Desktop.
Create and read fixed-point byte representations of numbers in Python
This file contains hidden or 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
import decimal | |
class FixedPoint(decimal.Decimal): | |
def to_fixed_point(self, whole_bits, fraction_bits, signed=False): | |
# returns bytes aligned to the last fraction bit | |
total = round(self * (1 << fraction_bits)) | |
num_bytes = (whole_bits + fraction_bits) / 8 | |
if num_bytes % 1: | |
num_bytes = num_bytes + 1 | |
return total.to_bytes(int(num_bytes), signed=signed, byteorder='big') | |
@classmethod | |
def from_fixed_point(cls, bytes_, whole_bits, fraction_bits, signed=False): | |
value = int.from_bytes(bytes_, byteorder='big', signed=signed) | |
if signed and value & sign: | |
value = -value | |
result = -(value & (sign - 1)) / (1 << fraction_bits) | |
else: | |
result = value / (1 << fraction_bits) | |
return cls.from_float(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment