On May 13, 12:45 pm, 7stud -- <bbxx789_0... / yahoo.com> wrote: > Chris Hulan wrote: > > On May 13, 9:57 am, I�áki Baz Castillo <i... / aliax.net> wrote: > >> Great ! > > >> -- > >> I�áki Baz Castillo > >> <i... / aliax.net> > > > I think ' '[0].to_s.hex will produce the value and be a bit easier to > > read. YMMV > > For example: > > x = " \tX" > > 0.upto(x.size-1){|i| puts "x%02x"%x[i].to_s.hex} > > Besides being a candidate to win a code obfuscation competition, your > code doesn't give the proper results. For instance, if you start with > the string "abc": > > x = "abc" > 0.upto(x.size-1){|i| puts "x%02x"%x[i].to_s.hex} > > --output:-- > x97 > x98 > x99 > > Those are the ascii values written with an x in front. You don't > convert decimal numbers to hex by merely writing an "x" in front of > them. The hex value x97 is equal to 9*16 + 7*1 = 151 in decimal, which > is not the ascii code for an "a". The ascii code for an "a" is 97. > > Your problems are a direct result of trying to cram all the code into > one line as well as using 'x' as a variable name, a character in the > string, a type specifier in the format string, and as the leading > charcacter in the output! > > This works: > > str = " \tC" > > 0.upto(str.length - 1) do |i| > ascii_code = str[i] > hex_str = ascii_code.to_s(16) > > if hex_str.length == 1 > hex_str = "0x0#{hex_str}" > else > hex_str = "0x#{hex_str}" > end > > puts hex_str > end > > --output:-- > 0x20 > 0x09 > 0x43 > > Or, you can use the cryptic format specifiers like this: > > str = " \tC" > > 0.upto(str.length - 1) do |i| > ascii_code = str[i] > dec_str = ascii_code.to_s > > puts "%#04x" % dec_str > end > > --output:-- > 0x20 > 0x09 > 0x43 > > -- > Posted viahttp://www.ruby-forum.com/. Thanks 7, i totally misrad what hex does...thats what I get for goofing off at work 9^) cheers