From: 7stud -- Date: 2008-05-14T01:45:49+09:00 Subject: Re: How to convert character to hexadecimal? Chris Hulan wrote: > On May 13, 9:57 am, I�aki Baz Castillo wrote: >> Great ! >> >> -- >> I�aki Baz Castillo >> > > 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 via http://www.ruby-forum.com/.