IQ
IQmathConv.py
#coding:utf-8
import sys
import math
Q=32 #bit幅
IQ_bit=11 #小数点位置
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) #整数部
DecNum=abs(iq-IntNum) #小数部
else:
IntNum=math.floor(iq) #整数部
DecNum=abs(iq-IntNum) #小数部
#小数部
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"
#負のとき
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 #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) #最上位bitの1or0判定
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)