[PYTHON] Mutual conversion between fixed point and binary numbers

IQ

IQmathConv.py



#coding:utf-8

import sys
import math

Q=32		#bit width
IQ_bit=11	#Decimal point position

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)	#Integer part
		DecNum=abs(iq-IntNum)	#Decimal part
	else:
		IntNum=math.floor(iq)	#Integer part
		DecNum=abs(iq-IntNum)	#Decimal part

	#Decimal part
	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"
	#When negative
	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's complement
		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 or 0 judgment of the most significant bit
		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)

[Reference](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

Mutual conversion between fixed point and binary numbers
Mutual conversion between Qiita articles and Jupyter notebook
Mutual conversion between date and days elapsed from January 1, 2000
Mutual conversion between JSON and YAML / TOML in Python
Conversion between singular and plural of words
Distinguish between numbers and letters with regular expressions
Relationship between Firestore and Go data type conversion
Conversion between Julian day and Gregorian calendar date
[Python] Conversion memo between time data and numerical data
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
How to convert floating point numbers to binary numbers in Python