1import numpy as np 2 3def q31sat(x): 4 if x > 0x7FFFFFFF: 5 return(np.int32(0x7FFFFFFF)) 6 elif x < -0x80000000: 7 return(np.int32(0x80000000)) 8 else: 9 return(np.int32(x)) 10 11q31satV=np.vectorize(q31sat) 12 13def toQ31(x): 14 """ 15 Return an array of Q31 scalars from an array of floats 16 17 :param x: array of float. 18 :type x: array 19 :return: array of Q31 scalars. 20 :rtype: array 21 22 """ 23 return(q31satV(np.round(np.array(x) * (1<<31)))) 24 25def q15sat(x): 26 if x > 0x7FFF: 27 return(np.int16(0x7FFF)) 28 elif x < -0x8000: 29 return(np.int16(0x8000)) 30 else: 31 return(np.int16(x)) 32 33q15satV=np.vectorize(q15sat) 34 35def toQ15(x): 36 """ 37 Return an array of Q15 scalars from an array of floats 38 39 :param x: array of float. 40 :type x: array 41 :return: array of Q15 scalars. 42 :rtype: array 43 44 """ 45 return(q15satV(np.round(np.array(x) * (1<<15)))) 46 47def q7sat(x): 48 if x > 0x7F: 49 return(np.int8(0x7F)) 50 elif x < -0x80: 51 return(np.int8(0x80)) 52 else: 53 return(np.int8(x)) 54 55q7satV=np.vectorize(q7sat) 56 57def toQ7(x): 58 """ 59 Return an array of Q7 scalars from an array of floats 60 61 :param x: array of float. 62 :type x: array 63 :return: array of Q7 scalars. 64 :rtype: array 65 66 """ 67 return(q7satV(np.round(np.array(x) * (1<<7)))) 68 69def Q31toF32(x): 70 """ 71 Return an array of float values from an array of Q31 values 72 73 :param x: Array of Q31 values. 74 :type x: array 75 :return: Array of float values. 76 :rtype: array 77 78 """ 79 return(1.0*np.array(x) / 2**31) 80 81def Q15toF32(x): 82 """ 83 Return an array of float values from an array of Q15 values 84 85 :param x: Array of Q15 values. 86 :type x: array 87 :return: Array of float values. 88 :rtype: array 89 90 """ 91 return(1.0*np.array(x) / 2**15) 92 93def Q7toF32(x): 94 """ 95 Return an array of float values from an array of Q7 values 96 97 :param x: Array of Q7 values. 98 :type x: array 99 :return: Array of float values. 100 :rtype: array 101 102 """ 103 return(1.0*np.array(x) / 2**7)