in reply to Re: Converting ASCII to Hex
in thread Converting ASCII to Hex

That did not seem to work My Hex codes are coming out like "313030" instead of things like "A5" or "0C" etc...

Replies are listed 'Best First'.
Re^3: Converting ASCII to Hex
by polettix (Vicar) on Jul 21, 2005 at 01:48 UTC
    If the input string is made of digits, you will see an hex like that you're describing. Consider that in ASCII the digits characters range from decimal 48, which is 0x30, to decimal 57, which is 0x39.

    If you have numbers that you want to treat like integers, and they're in the range 0-255, you can put a chr in the chain:

    #!/usr/bin/perl use strict; use warnings; my @values = (0, 1, 5, 25, 100, 200, 255); print join(", ", map { unpack "H*", chr } @values), $/; __END__ 00, 01, 05, 19, 64, c8, ff
    You may also consider printf/sprintf with the X indicator:
    #!/usr/bin/perl use strict; use warnings; my @values = (0, 1, 5, 25, 100, 200, 255, 500, 1000); print join(", ", map { sprintf "%X", $_ } @values), $/; __END__ 0, 1, 5, 19, 64, C8, FF, 1F4, 3E8
    Note that this second solution works well with numbers beyond 255. You can also pad with zeroes on the left, just look in the docs for sprintf.

    Flavio
    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Don't fool yourself.
Re^3: Converting ASCII to Hex
by friedo (Prior) on Jul 21, 2005 at 01:41 UTC
    Well, 313030 are the hex equivelents for the three characters "1", "0" and "0". Without knowing what your data is, we don't know if that's right or wrong. To clarify matters, are you sure you want the ASCII values of the characters, or do you want the hex representation of the number 100?
Re^3: Converting ASCII to Hex
by fishbot_v2 (Chaplain) on Jul 21, 2005 at 01:50 UTC

    You are missing what merlyn is saying. Use the unpack on the original string, not on the array of ordinals.

    If you run it on the ordinals, then you are converting strings that are made up of digits, so you will get back strings in the range 30..39.

    Update: The following should be more than sufficient to replace the logic in the OP:

    use strict; use warnings; open my $in, "<", "./infile"; my $input = do { local $/; <$in> }; open my $out, ">", "./outfile"; print $out unpack 'H*', $input;

    Though presumably you aren't hardcoding filenames in real life.

Re^3: Converting ASCII to Hex
by kwaping (Priest) on Jul 21, 2005 at 02:01 UTC
    Was your test string "100" by chance? :) 31 = hex 1, 30 = hex 0. You're getting the right output, it just doesn't look like what you expected.

    Here's an example you can try:
    my $text = 'WHY HELLO THERE!'; # split into array of individual characters my @characters = split(//,$text); # transform each one individually into uppercase hex foreach my $char (@characters) { $char = uc(unpack "H*", $char); } # print in quotes to demonstrate separation between array elements print "@characters";
    You can cross-check the results with http://www.lookuptables.com.