Skip to content

Instantly share code, notes, and snippets.

@vaiorabbit
Created October 22, 2016 07:06
Show Gist options
  • Save vaiorabbit/4e1c59df3574c80200026924e4e39b14 to your computer and use it in GitHub Desktop.
Save vaiorabbit/4e1c59df3574c80200026924e4e39b14 to your computer and use it in GitHub Desktop.
Shows the hexadecimal representation of a given floating point value.
# coding: utf-8
# ex.) $ ruby f2h.rb 1.0 -> 0000803f 00000000000000001000000000111111
require 'getoptlong'
def numeric?(str)
true if Float(str) rescue false
end
$cmd_opts = GetoptLong.new(
[ '-b', GetoptLong::NO_ARGUMENT ],
[ '-d', GetoptLong::NO_ARGUMENT ],
[ '-s', GetoptLong::NO_ARGUMENT ],
)
$opt_big = false
$opt_dbl = false
$opt_space = false
$cmd_opts.each do |opt, arg|
case opt
when '-b'; $opt_big = true
when '-d'; $opt_dbl = true
when '-s'; $opt_space = true
end
end
if $0 == __FILE__
values = ARGV.select {|arg| numeric?(arg) }
values.each do |value|
raw_str = [value.to_f].pack($opt_dbl ? 'D' : 'F').bytes
raw_str.reverse! if $opt_big
hex_str = raw_str.map {|byte| "%02x" % byte }.join($opt_space ? ' ' : '')
print "#{hex_str}\t"
bin_str = raw_str.map {|byte| "%08b" % byte }.join($opt_space ? ' ' : '')
print "#{bin_str}\n"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment