#将十进制浮点转化为二进制定点原码S12
def float2fix(f,int_bit = 3,decimal_bit = 12 ):
bit_num = int_bit + decimal_bit + 1
prec = 1 / 2 ** decimal_bit #精度
decimal_max = (2**12-1)*prec
num_max = 2**int_bit-1 + decimal_max
num_min = - 2**int_bit-1 + decimal_max
# print("The value range of fixed point:({0},{1})".format(num_min,num_max))
if f > 0 :
sign = "0"
else :
sign = "1"
f = abs(f)
data = int(f // prec)
quotient = "" #余数
while True:
remainder = data // 2
quotients = data % 2
quotient = quotient + str(quotients)
if remainder == 0:
break
else:
data = remainder
add_bit = bit_num - 1 - len(quotient)
if add_bit != 0:
quotient = quotient + "0"*add_bit + sign
else:
quotient = quoti
python——十进制浮点与有符号16位定点相互转化
最新推荐文章于 2024-04-11 14:07:32 发布