#!/bin/env ruby # ############################################################# # # author: mathias gumz # date : Don 26 Jun 2003 04:15:48 CEST # file : rbdc # about : digits-converter # ############################################################# # # # require 'getoptlong' $DELIM= /:/ $JOIN=':' $FORMAT= '' MANPAGE= < BUGS none atm END # returns the converted number def conv(how, number) case how when /d.*2h.*/ "%#{$FORMAT}x" % number when /h.*2d.*/ "%#{$FORMAT}d" % number.to_s.hex when /d.*2o.*/ "%#{$FORMAT}o" % number when /o.*2d.*/ "%#{$FORMAT}d" % number.to_s.oct when /h.*2o.*/ "%#{$FORMAT}o" % number.to_s.hex when /o.*2h.*/ "%#{$FORMAT}x" % number.to_s.oct when /d.*2b.*/ "%b" % number when /h.*2b.*/ "%b" % number.to_s.hex when /o.*2b.*/ "%b" % number.to_s.oct when /b.*2d.*/ r= 0 n= number.to_s.length - 1 number.to_s.each_byte { |b| r+= (b-48) * (2**n); n-= 1 } return r when /b.*2h.*/ "%#{$FORMAT}x" % conv("bin2dec", number) when /b.*2.*/ "%#{$FORMAT}o" % conv("bin2dec", number) end end # main loop begin opts= GetoptLong.new opts.set_options( [ "--help", "-h", GetoptLong::NO_ARGUMENT ], [ "--delim", "-d", GetoptLong::REQUIRED_ARGUMENT ], [ "--format", "-f", GetoptLong::REQUIRED_ARGUMENT ], [ "--join", "-j", GetoptLong::REQUIRED_ARGUMENT ] ) opts.each do |o,a| case o when /--help/ puts MANPAGE exit 0 when /--delim/ $DELIM= a when /--join/ $JOIN= a end end how = ARGV[0] r= ARGV[1].split($DELIM) 0.upto(r.size-1) do |i| r[i]= conv(how, r[i]) end puts r.join($JOIN) end