From: 7stud -- Date: 2008-05-18T12:59:21+09:00 Subject: Re: Hex to decimal? Tim Hunter wrote: > Since nobody else has any Ruby to talk about today... :-) > > My gut feel is that this should be 2 or 3 lines of code but for some > reason I'm missing the trick. > > I need a script that converts pairs of hex digits into their decimal > equivalents. Suppose the script accepts a single argument, a string > composed of hex digits, either upper- or lower-case, or both, possibly > with embedded blanks. For the sake of argument let's say that there's > always going to be at least 1 pair but never more than, oh, 20 pairs (or > as many as can easily be typed on a command line). > > The script should remove any embedded blanks from the argument, then go > through the string left-to-right. For each pair of hex digits, display > the value of the pair as a 3-digit decimal number, separated with a > backslash. > > So, for example, > > ruby hex2dec.rb "f0 d7e2 28" => \240\215\226\040 > > Ideas? hex_str = ARGV[0] hex_str = hex_str.delete(" ") results = [] stop_index = hex_str.length - 2 0.step(stop_index, 2) do |i| decimal_num = hex_str[i,2].hex results << sprintf("%03d", decimal_num) end out_str = results.join("\\") puts out_str $ ruby r1test.rb "F0 d7E2 28" 240\215\226\040 -- Posted via http://www.ruby-forum.com/.