RockPaperScissors

LizardSpock

 

fixed_point

A Ruby Gem for modeling fixed point data types. Useful for converting between numbers in hex, binary and decimal.

There are simple method built into ruby for this, binary to decimal '0110'.to(2), decimal to hex 100.to_s(16). However these methods do not handle fractional and signed numbers.

Usage

4 bit Positive number

require 'fixed_point'

format = FixedPoint::Format.new(1,4,0)
fixt   = FixedPoint::Number.new(2.0, format)

fixt.source   #=> 2.0
fixt.to_f.    #=> 2.0
fixt.to_i.    #=> 2
fixt.frac     #=> 0.0
fixt.to_h     #=> "2"
fixt.to_b     #=> "0010"

8 Bit (4 Integer, 4 Fractional) Negative Fractional Numbers:

require 'fixed_point'

format = FixedPoint::Format.new(1,4,4)
fixt   = FixedPoint::Number.new(-2.25, format, "_")

fixt.source   #=> -2.25
fixt.to_f     #=> -2.25
fixt.to_i     #=> -2
fixt.frac     #=> -0.25
fixt.to_h     #=> "dc"
fixt.to_b     #=> "1101_1100"

Building tables:

require 'fixed_point'

#Signed 8 bit, (4 bit Integer, 4 bit fractional)
format = FixedPoint::Format.new(1,4,4)

table_for_conversion = [ 
  2.7505, 2.5, 2.25, 2, 0.5, 0, -0.5, -4.5   
]

table_for_conversion.each do |num|
  fixt   = FixedPoint::Number.new(num, format, '_')
  puts "#{format.width}'b#{fixt.to_b}  // Quantised %7.4f  Source %7.4f" % [ fixt.to_f, fixt.source]
end

Gives :

8'b0010_1100  // Quantised  2.7500  Source  2.7505
8'b0010_1000  // Quantised  2.5000  Source  2.5000
8'b0010_0100  // Quantised  2.2500  Source  2.2500
8'b0010_0000  // Quantised  2.0000  Source  2.0000
8'b0000_1000  // Quantised  0.5000  Source  0.5000
8'b0000_0000  // Quantised  0.0000  Source  0.0000
8'b1111_1000  // Quantised -0.5000  Source -0.5000
8'b1011_1000  // Quantised -4.5000  Source -4.5000

Download/Install

gem install fixed_point

Or visit RubyGems

Requirements

Ruby
Windows/Mac OS X/Linux/Unix

Source

GitHub