我正在尝试为半精度浮点类型实现binary16编码。
除了一个细节之外,代码正在工作:它返回具有三个属性(符号、指数、分数)的对象,但我希望它返回浮点。现在,我必须打电话给to_f才能到达浮点数。我希望这是集成的int类和float类的工作方式。
这是我的密码:
require 'bindata'
class Binary16Be < BinData::Record
# naming based on https://en.wikipedia.org/wiki/Half-precision_floating-point_format
bit1 :sign_bit
bit5 :exponent
bit10 :fraction
def sign
sign_bit.zero? ? 1 : -1
end
def to_f
if exponent == 31 # special value in binary16 - all exponent bits are 1
return fraction.zero? ? (sign * Float::INFINITY) : Float::NAN
end
sign * 2**(exponent - 15) * (1.0 + fraction.to_f / 1024)
end
end我想要的:
Binary16Be.read("\x3C\x00")
=> 1.0现在发生了什么:
Binary16Be.read("\x3C\x00")
{:sign_bit=>0, :exponent=>15, :fraction=>0}发布于 2017-04-07 18:54:47
(这其实不是我自己的答案,我是从创业板的作者那里得到的。对他的答案做了一些修改,使其更符合这个问答格式。)
程序描述为在bindata Wiki /基元类型中。
就你而言:
Primitive而不是Record#to_f重命名为#get#set转换码
class Binary16Be < BinData::Primitive
# naming based on
# https://en.wikipedia.org/wiki/Half-precision_floating-point_format
bit1 :sign_bit
bit5 :exponent
bit10 :fraction
def sign
sign_bit.zero? ? 1 : -1
end
def get
if exponent == 31 # special value in binary16 - all exponent bits are 1
return fraction.zero? ? (sign * Float::INFINITY) : Float::NAN
end
sign * 2**(exponent - 15) * (1.0 + fraction.to_f / 1024)
end
def set(val)
self.sign = (val >= 0.0)
self.fraction = ... # TODO implement
self.exponent = ... # TODO implement
end
endhttps://stackoverflow.com/questions/43276945
复制相似问题