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

I've been looking all over for code or instruction and how to convert ascii to hex and oct, and then back. (Similar to this node: One-liner ascii/bin) Anyone have any hints or code or a node that has this? All my searches have turned up the same nodes that have the word ASCII in them :(

Thanks.

Replies are listed 'Best First'.
Re: hex to ascii, oct to ascii, and back?
by data64 (Chaplain) on Mar 05, 2002 at 03:58 UTC

    I am not sure what exactly you mean by ascii to hex and oct. Are you talking about converting a string representation like "0755" or "0x55" ? If yes, then look at oct and hex.

    Otherwise maybe you want to get the ascii value of a character and represent it as oct or hex. Use ord to get the ascii value and then printf %o for oct and printf %x for hex. The formatting codes for printf are explained here

    Update:

    After re-reading the link you included I think I have a better understanding of what you are asking for. Some code below

    octal

     perl -e 'printf("%o", ord) foreach ( split //, shift )'

    hex

     perl -e 'printf("%x", ord) foreach ( split //, shift )'

    <cite>Just a tongue-tied, twisted, earth-bound misfit. -- Pink Floyd</cite>

      o = Octal integer
      x = Hexadecimal integer
      :(
Re: hex to ascii, oct to ascii, and back?
by particle (Vicar) on Mar 05, 2002 at 03:57 UTC
Re: hex to ascii, oct to ascii, and back?
by ajwans (Scribe) on Mar 05, 2002 at 04:09 UTC
    Lookup the perldoc on pack and unpack (and printf)

    my @hex = unpack ("h*", $ascii_string); foreach my $hex (@hex) { printf ("%c", hex ($hex)); }
Re: hex to ascii, oct to ascii, and back?
by strat (Canon) on Mar 05, 2002 at 10:14 UTC
    Maybe you'll find sprintf more interesting for converting than printf...
    my $char = 'm'; my $octal = sprintf("%03o", ord($char)); my $hex = sprintf("%02X", ord($char)); print "Oktal: $octal\tHex: $hex\n";

    Best regards,
    perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

Re: hex to ascii, oct to ascii, and back?
by Anonymous Monk on Mar 05, 2002 at 05:15 UTC