IQ
IQmathConv.py
#coding:utf-8
import sys
import math
Q=32 #Bitbreite
IQ_bit=11 #Punktposition
def d_to_IQ(d):
d_bin=format(d,'b').zfill(Q)
ret=0.0
for b in range(Q,-1,-1):
bin_value_str=d_bin[b:b+1]
if(len(bin_value_str)<1):
continue
bin_value=int(bin_value_str)
if ((Q-b)==Q) and (bin_value==1):
ret *= -1
else:
if(bin_value==1):
ret += pow(2, ((Q-b)-(IQ_bit+1)))
return ret
def IQ_to_d(iq):
Flag=0
IntBit=Q-IQ_bit-1
DecBit=IQ_bit
BitLength=IntBit+DecBit+1
IntOut = ""
DecOut = ""
DecTemp = 0.0
if iq<0:
IntNum=-math.floor(-iq) #Ganzzahliger Teil
DecNum=abs(iq-IntNum) #Dezimalteil
else:
IntNum=math.floor(iq) #Ganzzahliger Teil
DecNum=abs(iq-IntNum) #Dezimalteil
#Dezimalteil
for i in range(1, IQ_bit+1):
if DecNum==0:
DecOut+="0"
else:
DecNum*=2
if DecNum>=1:
DecOut+="1"
DecNum-=1
else:
DecOut+="0"
#Wenn negativ
if iq < 0:
for i in range(1, DecBit+1):
DecTemp+= int(DecOut[-i]) * pow(2, (i-1))
DecTemp = (pow(2, (DecBit+1))-1) - DecTemp #Ergänzung von 2
DecTemp+=1
if DecTemp >= pow(2, (DecBit+1)):
Flag=1
DecOut=""
for i in range(DecBit-1, -1, -1):
SignBit=(int(DecTemp) & pow(2, i))
if SignBit!=0:
DecOut+= "1"
else:
DecOut+="0"
if iq>=0:
IntNum=int(IntNum)
else:
IntNum=pow(2, (IntBit+1))-1+int(IntNum)
if Flag==1:
IntNum+=1
for i in range(1, (IntBit+1)+1):
SignBit=IntNum & pow(2, IntBit) #1 oder 0 Beurteilung des höchsten Bits
if SignBit!=0:
IntOut+="1"
else:
IntOut+="0"
IntNum*=2
if IntNum >= (pow(2, (IntBit+1))-1):
IntNum-=(pow(2, (IntBit+1))-1)
return IntOut+DecOut
print d_to_IQ(364)
b=IQ_to_d(-1.50473253979636)
print b
print int(b,2)
[Referenz](http://yound.hatenablog.com/entry/2016/12/26/%E7%AC%A6%E5%8F%B7%E4%BB%98%E3%81%8D%E5%9B % BA% E5% AE% 9A% E5% B0% 8F% E6% 95% B0% E7% 82% B9% E6% BC% 94% E7% AE% 97% E3% 81% AE% E5% BD% A2 % E5% BC% 8F% E5% A4% 89% E6% 8F% 9B% E5% 87% A6% E7% 90% 86)
Recommended Posts