How do I output a string of hex values into a binary file in Perl? -


i'm trying read in binary file, store data string of hex values, use regular expressions modify hex values, , spit data out new binary file (that modified version of original).

i can of steps except last one. when open new binary file in hex editor, seems wrong... want how hex string is, in hex editor.

here i'm attempting when creating new file:

# format data string array file processing @data_ary = unpack('h*', $data_str);  generate_new_file($filname, \@data_ary);   sub generate_new_file {      $fname = "mod -" . shift(@_);      $aref = shift(@_);       open(bin, ">", $fname) or die;      binmode(bin);       $nybble(@$aref)      {          print (bin $nybble)      }      close(bin); } 

i'm guessing problem has use of unpack. i'm not sure how else huge hex string form read hex , not ascii characters. suggestions appreciated!

the code shown above trying output data new file. have hex want output in $data_str. unpack attempt string of hex list of hex values.

i'm getting closer. removed unpack beginning since data single string of hex. split , put array. @ least gets size of file correct now. however, new problem it's cropping off second part of every byte , replacing 0 (when viewed in hex editor)... when print, elements of array correct data. ideas? new code below:

# format data string array file processing @data_ary = split //, $data_str; generate_new_file($filname, \@data_ary);   sub generate_new_file {      $fname = "mod -" . shift(@_);      $aref = shift(@_);       open(bin, ">", $fname) or die;      binmode(bin);       (my $i = 0; $i < @$aref; $i += 2)      {          ($hi, $lo) = @$aref[$i, $i+1];          print bin pack "h", $hi.$lo;      }       close(bin); } 

i figured out! forgot "*" when calling pack, more first character! finished code below. amon!

# format data string array file processing @data_ary = split //, $data_str; generate_new_file($filname, \@data_ary);   sub generate_new_file {      $fname = "mod -" . shift(@_);      $aref = shift(@_);       open(bin, ">", $fname) or die;      binmode(bin);       (my $i = 0; $i < @$aref; $i += 2)      {          ($hi, $lo) = @$aref[$i, $i+1];          print bin pack "h*", $hi.$lo;      }      close(bin); } 

here, unpack returns single string, not array of values. if want have array of hex characters (each denoting 4 bits), have split resulting string:

my @data = split //, unpack "h*", $data; 

(use split /..\k/, $data split byte-equivalents)

before printing data filehandle, have pack original data again. recommend @ least on 8-bit parts of original data:

for (my $i = 0; $i < @$aref; $i += 2) {    ($hi, $lo) = @$aref[$i, $i+1];    print out pack "h*", $hi.$lo; } 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -