普通浮点数转半精度工具实现
来源:互联网 发布:rewear it aac 编辑:程序博客网 时间:2024/06/10 22:23
工作中遇到的小工具制作,直接压成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-8import mathimport redef Real2HalfFloat(data):MINNUM = -65536MAXNUM = 65535FloatVal = 0if data:if data < MINNUM:data = MINNUMif data > MAXNUM:data = MAXNUMsign = 0if data < 0:sign = 1data = -dataexp = math.floor((math.log2(data)))expout = exp + 16Mantial = round(data / pow(2, exp - 10)) - 1024if expout <= 0:FloatVal = 0else:FloatVal = sign * 32768 + expout * 1024 + Mantialreturn FloatValdef 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 + imagif imag and not real:fw.write('0x0000' + "%X" % result + '\n')elif not imag and not real:fw.write('0x00000000' + '\n')else:fw.write('0x' + "%X" % result + '\n')elif len(input[i]) == 1:result = Real2HalfFloat(float(input[i][0]))if result:fw.write('0x' + "%X" % result + '\n')else:fw.write('0x0000' + '\n')if __name__ == '__main__':print('Tips: Input number 0 if you want to exit!\n')while True:sourcfile = input("input source file:\n")if sourcfile is '0':breakReadCfloatData(sourcfile)print('Transfer Success!')
阅读全文
0 0
- 普通浮点数转半精度工具实现
- C++实现双精度浮点数四则运算
- 单精度浮点数乘法的实现
- 浮点精度
- 单精度浮点数 二进制的转换 C++实现
- PHP浮点精度问题
- 浮点数精度
- 浮点精度转换
- 浮点数精度
- 浮点数精度错误
- 浮点精度转换
- 浮点数精度问题
- java浮点精度总结
- JAVA 浮点精度问题
- 单精度浮点数
- 浮点数精度
- 浮点精度问题
- 浮点数精度
- AngularJS指令参数详解
- js 高级函数特性
- AndroidStudio将项目上传至github代码仓库步骤
- 21:二维数组右上左下遍历(1.8编程基础之多维数组)
- matlab 两幅图像配准
- 普通浮点数转半精度工具实现
- iOS11新增技术功能总结
- 一、jQuery ——淡入淡出
- 单链表中重复元素的删除
- 解密HLS中的AES加密
- mysql 批量插入
- JAVA使用随机数进行概率抽奖
- Loadrunner性能指标分析
- caffe第一步,配置VS2015环境。