converting a line of ascii to decimal

X

xtrimnx

Okay, so I'm trying to read in the file and take each character one at
at time and convert them to their numeric equivilants. So far this
program just gets me the 1st charachter of each line and changes it.
open OUTPUT,">fileout";
open INPUT, "<filein";
while(<INPUT>) {
$val = unpack('c', $_);
print OUTPUT "$val\n";
$val2 = pack('U', $val);
print OUTPUT "$val2\n";
}
close INPUT;
close OUTPUT;
 
G

Gunnar Hjalmarsson

xtrimnx said:
Okay, so I'm trying to read in the file and take each character one at
at time and convert them to their numeric equivilants. So far this
program just gets me the 1st charachter of each line and changes it.
open OUTPUT,">fileout";
open INPUT, "<filein";
while(<INPUT>) {
$val = unpack('c', $_);
print OUTPUT "$val\n";
$val2 = pack('U', $val);
print OUTPUT "$val2\n";
}
close INPUT;
close OUTPUT;

while (<INPUT>) {
print OUTPUT $_;
s/(.)/unpack 'c', $1/eg;
print OUTPUT $_;
}
 
T

Ted Zlatanov

Okay, so I'm trying to read in the file and take each character one at
at time and convert them to their numeric equivilants. So far this
program just gets me the 1st charachter of each line and changes it.
open OUTPUT,">fileout";
open INPUT, "<filein"; while(<INPUT>) { $val = unpack('c', $_); print OUTPUT
"$val\n"; $val2 = pack('U', $val); print OUTPUT "$val2\n"; }
close INPUT;
close OUTPUT;

The reason your way doesn't work is that the pack/unpack logic is
incorrect. Here's the right solution:

perl -n -e 'chomp; @out = unpack "c*", $_; print "@out\n"'

Basically, you don't need to repack the values (if you do, you'll just
get the original string), and you need an array instead of a scalar.

Here's an alternate solution:

perl -n -e 'chomp; @out = map { ord } split //, $_; print "@out\n"'

Ted
 
J

Jay Tilton

: Okay, so I'm trying to read in the file and take each character one at
: at time and convert them to their numeric equivilants.

printf '%*vd', ' ', $_;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top