def dec2bin(number, int_bits, frac_bits, decimal_mark)
negative = false
if (number < 0)
negative = true
number = -number
end
## Create Integer only number
number_int = Integer(number);
## Create Fractional only number
number_frac = number - number_int;
## Create Integer Binary String
ret_bin_int = "";
## Create Fractional Binary String
ret_bin_frac = "";
##Integer
ret_bin_int = number_int.to_s(2) ;
padding_bits = int_bits - ret_bin_int.length ;
begin
ret_bin_int = Array.new(padding_bits, "0").join + ret_bin_int ;
rescue
puts "ERROR not enough integer bits to represent #{number}";
return -1;
end
## Fractional
ret_bin_frac = ""
fractional = 0
if (frac_bits > 0)
ret_bin_frac = Integer(number_frac * 2**frac_bits).to_s(2);
padding_bits = frac_bits - ret_bin_frac.length ;
ret_bin_frac = Array.new(padding_bits, "0").join + ret_bin_frac ;
fractional = ret_bin_frac.to_i(2).to_f / (2**frac_bits)
end
if (negative == true)
number = (ret_bin_int + ret_bin_frac).to_i(2)
#Perforrm this binary operation number = -number + 1
#In an integer number space
number = 2**(int_bits+frac_bits) - number
ret_bin_int = number.to_s(2)[0,int_bits]
ret_bin_frac = number.to_s(2)[int_bits, frac_bits]
end
binary = ret_bin_int + decimal_mark + ret_bin_frac;
## ret_bin Add decimal marker
return {
:binary => binary,
:int => number_int,
:frac => fractional,
:real => (fractional+number_int)
}
end
Example using the function:
intBits = 6
fracBits =4
converted = dec2bin(10.5, intBits, fracBits, "_")
puts converted[:binary]
NOTE:
Since first post I have fixed a fracbits=0 bug and now works with negative numbers (converting to a twos complement format)
No comments:
Post a Comment