ruby - Implement a basic datatype in BinData -


i trying implement binary16 encoding half-precision floating point type.

the code working except 1 detail: returns object 3 properties (sign, exponent, fraction), return float. right now, have call to_f float. work way integrated int , float classes work.

here's code:

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 - exponent bits 1       return fraction.zero? ? (sign * float::infinity) : float::nan     end     sign * 2**(exponent - 15) * (1.0 + fraction.to_f / 1024)   end end 

what like:

binary16be.read("\x3c\x00") => 1.0 

what happens right now:

binary16be.read("\x3c\x00") {:sign_bit=>0, :exponent=>15, :fraction=>0} 

(this not own answer, received gem's author. made slight alterations answer fit q&a format little better.)

the procedure described in bindata wiki / primitive types

in case:

  1. subclass primitive instead of record
  2. rename #to_f #get
  3. implement #set

the converted code

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     if exponent == 31 # special value in binary16 - exponent bits 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 end 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -