zoukankan      html  css  js  c++  java
  • 普通浮点数转半精度工具实现

    工作中遇到的小工具制作,直接压成exe就可以用了

    功能:输入文件,将文件中的一列浮点转为一列半精度浮点(半精度浮点)或者两列浮点转为一列复数型半精度浮点,输出为同级目录源文件名+Out.dat,输入0退出

    case1:文件中是一行数据0.5,那么输出就是0x3c00

    case2:文件中一行数据是 0.5 0或者0 0.5;输出就是0x3C000000和0x00003C00

    #! /usr/bin/env python
    # encoding:utf-8
    # ! /usr/bin/env python
    # encoding:utf-8
    import math
    import re
    
    
    def Real2HalfFloat(data):
    	MINNUM = -65536
    	MAXNUM = 65535
    	FloatVal = 0
    	if data:
    		if data < MINNUM:
    			data = MINNUM
    		if data > MAXNUM:
    			data = MAXNUM
    		
    		sign = 0
    		if data < 0:
    			sign = 1
    			data = -data
    		
    		exp = math.floor((math.log2(data)))
    		expout = exp + 16
    		
    		Mantial = round(data / pow(2, exp - 10)) - 1024
    		
    		if expout <= 0:
    			FloatVal = 0
    		else:
    			FloatVal = sign * 32768 + expout * 1024 + Mantial
    	return FloatVal
    
    
    def ReadCfloatData(sourcefile):
    	input = []
    	with open(sourcfile, 'r') as f:
    		for line in f.readlines():
    			line = line.strip()
    			line = re.sub('s+',' ',line) #两个数字间多个空格
    			input.append(line.split(' '))
    	destfile = sourcefile.replace('.dat', '')
    	destfile = destfile.replace('.txt', '')
    	destfile += 'Out.dat'
    	with open(destfile, 'w') as fw:
    		for i in range(len(input)):
    			if len(input[i]) == 2:
    				real = Real2HalfFloat(float(input[i][0]))
    				imag = Real2HalfFloat(float(input[i][1]))
    				result = real * 65536 + imag
    				if imag and not real:
    					fw.write('0x0000' + "%X" % result + '
    ')
    				elif not imag and not real:
    					fw.write('0x00000000' + '
    ')
    				else:
    					fw.write('0x' + "%X" % result + '
    ')
    			elif len(input[i]) == 1:
    				result = Real2HalfFloat(float(input[i][0]))
    				if result:
    					fw.write('0x' + "%X" % result + '
    ')
    				else:
    					fw.write('0x0000' + '
    ')
    
    
    if __name__ == '__main__':
    	print('Tips: Input number 0 if you want to exit!
    ')
    	while True:
    		sourcfile = input("input source file:
    ")
    		if sourcfile is '0':
    			break
    		ReadCfloatData(sourcfile)
    		print('Transfer Success!')
    

      

  • 相关阅读:
    想更改Github仓库中的某个文件结构
    记git一些基本用法
    剑指Offer-Python(16-20)
    剑指Offer-Python(11-15)
    初次使用flask
    Python的Cmd模块的简易运用学习
    SQL-全称量词查询
    线段树模板1
    OJ输入输出超时(C++)
    二叉查找树(BST)定义
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8006786.html
Copyright © 2011-2022 走看看