Converting hexadecimal string to character

If I have a string that represents some character in hex, what is the
easiest way to convert it to that character? For example, if I have
the string "41" how do I convert it to "\x41" (or "A")? I've been
toying around with eval and sprintf, but can't seem to get it right.
Right now I'm using the brute force approach below, but I think there
must be a better way.

c = "41"
eval("\"\\x#{c}\"")

···

--
Michael Jackson
http://mjijackson.com
@mjijackson

Michael Jackson wrote:

If I have a string that represents some character in hex, what is the
easiest way to convert it to that character? For example, if I have
the string "41" how do I convert it to "\x41" (or "A")? I've been
toying around with eval and sprintf, but can't seem to get it right.
Right now I'm using the brute force approach below, but I think there
must be a better way.

c = "41"
eval("\"\\x#{c}\"")

--
Michael Jackson
http://mjijackson.com
@mjijackson

This should work

irb(main):002:0> "%c" % "41".to_i(16)
=> "A"

Michael Jackson wrote:

If I have a string that represents some character in hex, what is the
easiest way to convert it to that character? For example, if I have
the string "41" how do I convert it to "\x41" (or "A")? I've been
toying around with eval and sprintf, but can't seem to get it right.
Right now I'm using the brute force approach below, but I think there
must be a better way.

c = "41"
eval("\"\\x#{c}\"")

c="41"
puts c.hex.chr # prints A

HTH gfb

···

--
Posted via http://www.ruby-forum.com/\.

Excellent. Both of these suggestions work beautifully. Clearly I need
to familiarize myself better with sprintf and String.

Thanks!

···

--
Michael Jackson

@mjijackson

On Sat, May 15, 2010 at 9:22 AM, Gianfranco Bozzetti <gf.bozzetti@alice.it> wrote:

Michael Jackson wrote:

If I have a string that represents some character in hex, what is the
easiest way to convert it to that character? For example, if I have
the string "41" how do I convert it to "\x41" (or "A")? I've been
toying around with eval and sprintf, but can't seem to get it right.
Right now I'm using the brute force approach below, but I think there
must be a better way.

c = "41"
eval("\"\\x#{c}\"")

c="41"
puts c.hex.chr # prints A

HTH gfb
--
Posted via http://www.ruby-forum.com/\.

Michael Jackson wrote:

Excellent. Both of these suggestions work beautifully. Clearly I need
to familiarize myself better with sprintf and String.

Another way:

irb(main):001:0> ["41"].pack("H*")
=> "A"

This has the added benefit of being able to work on sequences of
characters in one go.

irb(main):002:0> ["414243"].pack("H*")
=> "ABC"

···

--
Posted via http://www.ruby-forum.com/\.