http://www.perlmonks.org?node_id=191039

semio has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking for ways to convert a given hex value to its char equivalent. For example, converting hex 61 should result in char "a", hex 62 should convert to char "b", etc. I spent some time with available functions for converting values, e.g. I looked at perlfunc hex, but it is used for converting from hex to dec. I also looked at perlfunc pack but this didn't appear to present the results I'm looking for.

cheers! -semio

Replies are listed 'Best First'.
Re: converting hex to char
by DamnDirtyApe (Curate) on Aug 19, 2002 at 00:01 UTC

    You want to use either chr, or sprintf's %c.

    perl -e 'print map { chr } 0x61, 0x62, 0x63' perl -e 'printf "%c%c%c", 0x61, 0x62, 0x63'

    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche
•Re: converting hex to char
by merlyn (Sage) on Aug 19, 2002 at 02:37 UTC
      thanks DamnDirtyApe, adrianh, sauoq and merlyn for the great advice. To give you an idea as for the basis of my question, I'm interesting in building a small tool that will convert hex content in a Snort IDS signature to a char value and, conversely, take a known attack string and quickly convert it to hex for signature creation. I'll probably use something like
      print unpack "H*", "abc";
      for the char to hex conversion.

      cheers! -semio

Re: converting hex to char
by adrianh (Chancellor) on Aug 19, 2002 at 00:10 UTC

    Use chr with hex... for example

    use strict; use warnings; use Test::More tests => 1; is(chr(hex('62')), 'b', 'hex -> char worked');
    gives us
    1..1 ok 1 - hex -> char worked
    Hope this helps.
Re: converting hex to char
by sauoq (Abbot) on Aug 19, 2002 at 00:40 UTC
    TIMTOWTDI and all that. . .
    perl -le 'print pack "ccc", 0x61, hex(62), hex("63")'
    -sauoq
    "My two cents aren't worth a dime.";