0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

固定小数点と2進数相互変換

Posted at

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)

参考

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?