Python中的十进制到二进制半精度IEEE 754

时间:2015-10-31 12:52:05

标签: python numpy floating-point precision ieee-754

我只能使用struct.pack模块将小数转换为二进制单精度IEEE754,或者使用numpy.frombuffer

执行相反的操作(float16或float32)

是否可以使用Numpy?

将小数转换为二进制半精度浮点数

我需要打印转化结果,因此如果我输入"117.0",则应打印"0101011101010000"

2 个答案:

答案 0 :(得分:7)

  

如果我输入" 117.0",则应打印" 0101011101010000"

>>> import numpy as np
>>> bin(np.float16(117.0).view('H'))[2:].zfill(16)
'0101011101010000'

答案 1 :(得分:3)

float16建议的Mark Dickinson方法必须后跟# http://ruby-doc.org/stdlib-2.0.0/libdoc/open-uri/rdoc/OpenURI.html require 'open-uri' # https://github.com/flori/json require 'json' # http://stackoverflow.com/questions/9008847/what-is-difference-between-p-and-pp require 'pp' buffer = open('http://api.cryptocoincharts.info/tradingPair/eth_btc').read # api_key = "FtHwuH8w1RDjQpOr0y0gF3AWm8sRsRzncK3hHh9" result = JSON.parse(buffer) puts result["markets"] # result.each do |user| # puts "#{user['id']}\t#{user['name']}\t#{user['email']}" # puts "Registered: #{user['created_at']}\n\n" # end # my_hash = JSON.parse('{"hello": "goodbye"}') # puts my_hash["hello"] => "goodbye" 方法才能获得所需的二进制表示形式:

tostring()