Skip to content

Instantly share code, notes, and snippets.

@MicahStevens
Created March 1, 2016 03:41
Show Gist options
  • Save MicahStevens/4e83da4235d5471c196e to your computer and use it in GitHub Desktop.
Save MicahStevens/4e83da4235d5471c196e to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from __future__ import division
"""
Some functions for converting to and from two's compliment.
Useful for dealing with DSP functions in microcontrollers that you may want to
control with floating point coefficients and variables, but the processor stores everything
as int's..
All conversions assume you are dealing with 16 bit integer storage.
author: Micah Stevens <micahstev@gmail.com>
"""
import numpy as np
def float2twos(val):
"""
returns a signed integer representation of a floating point number. (16 bit)
Parameters
----------
val: signed 16 bit int.
"""
return int2twos(int(round(val * (2**15))))
def twos2float(val):
"""
returns a floating point representation of a signed int. (16bit)
Parameters
----------
val: floating point number from -1 to 1.
"""
return round(twos2int(val) / 2**15, 4)
def int2twos(val):
"""
Converts a signed int to 2's compliment unsigned int.
Parameters
----------
val: signed int, from -0x7fff to 0x7fff
"""
if val < 0:
return 2**16 + val
else:
return val
def twos2int(val):
"""
Converts an unsigned 2's compliment int to a signed int (15 bit)
Parameters
----------
val: 2's compliment unsigned int
"""
if val & 0x8000 == 0x8000:
val = 2**16 - val
return val
def float2hex(val):
"""
Converts a signed floating point number to a two's compliment 16 bit hex string.
Parameters
-----------
val: a floating point number from -1 to 1.
"""
return format(float2twos(val),'x')
def hex2float(val):
"""
Converts a 4 digit hex string to a signed floating point number from -1 to 1.
Parameters
----------
val: 4 character hex string. 16 bit. Don't use '0x' at the beginning.
"""
val = int(val, 16)
return twos2float(val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment