You seem to want output that consistently shows two hex digits per ASCII character, with leading zero where needed.
So use sprintf (and use ALL_CAPS for a file handle name, or else use a lexically scoped scalar variable, instead of a lower-case bare word; and don't bother holding the whole file content in an array):
If "map" is foreign to you, you can use a loop like the following, but you should learn to like map because in this kind of case it'll probably run faster than the for loop):use strict; open( IN, "file.txt" ) or die "file.txt: $!"; open( OUT, "out.txt" ) or die "out.txt: $!"; # or: open( my $in, "file.txt") ... while (<IN>) { # or: while (<$in> ...) $_ = join "", map { sprintf("%2.2x",ord($_)) } split //; print OUT $_, $/; }
For that matter, when doing a simple "in->out" text filter like this, I prefer not to use open at all -- just while (<>) { ... print; } -- then provide the input file name as a command line arg, and redirect STDOUT to some other file.my $outstr = ""; $outstr .= sprintf("%2.2x",ord($_)) for (split //); print $outstr, $/;
In reply to Re: Converting ASCII to Hex
by graff
in thread Converting ASCII to Hex
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |