[英]perl file to hex number 82?
Trying to do binary to hex conversion on a file. 尝试对文件进行二进制到十六进制的转换。 I can output the hex but however when I try to output the result to a file,variable it returns the string "82".
我可以输出十六进制,但是当我尝试将结果输出到文件中时,变量将返回字符串“ 82”。 I cannot understand why;
我不明白为什么; like all things most likely something simple.
喜欢所有事物,最有可能是简单的事物。
#!/usr/bin/perl -w
use strict;
my $blockSize = 1024;
my $fileName = $ARGV[0];
my $hexName = $ARGV[1];
open(F,"<$fileName") or die("Unable to open file $fileName, $!");
binmode(F);
my $buf;
my $ct=0;
while(read(F,$buf,$blockSize,$ct*$blockSize)){
foreach(split(//, $buf)){
printf unpack ("H*", $_); #prints the hex stream to terminal just fine
open(H,">$hexName") or die("Unable to open file $fname, $!");
binmode (H);
printf H unpack ("H*", $_);
close (H);
}
print "\n";
$ct++;
}
close(F);
Output 产量
perl rawrHexFile.pl test.png file.hex
89504e470d0a1a0a0000000....
mookie@temple:/srv/bench % cat file.hex 82 mookie @ temple:/ srv / bench%cat file.hex 82
cat file.hex
82
Thanks. 谢谢。
Here's my final code which works. 这是我的最终代码。 in case of
的情况下
use strict;
my $fileName = $ARGV[0];
my $hexName = $ARGV[1];
my $hexCodeFile = $ARGV[2];
my $hexDecodeFile = $ARGV[3];
my $blockSize = -s $fileName;
my $buf;
open(F,"<$fileName") or die("Unable to open file $fileName, $!");
binmode(F);
open(H,">$hexName") or die("Unable to open file $hexName, $!");
read(F,$buf,$blockSize);
print H unpack ("H*", $buf);
close (H);
close(F);
You recreate the file (open >) for each byte of the input file, so you only get the output for the last byte of the input file. 您为输入文件的每个字节重新创建文件(打开>),因此仅获得输入文件最后一个字节的输出。 Open the file outside of the loop.
在循环外打开文件。
Also, you keep appending to $buf
rather than replacing its content, so your output will look like AABABCABCDABCDE instead of the desired ABCDE (where each letter represents the output for 1024 bytes of input) 同样,您继续追加
$buf
而不是替换其内容,因此您的输出将看起来像AABABCABCDABCDE而不是所需的ABCDE(其中每个字母代表输入1024字节的输出)
Fixed: 固定:
use strict;
use warnings qw( all );
use constant BLOCK_SIZE => 64*1024;
my ($in_qfn, $out_qfn) = @ARGS;
open(my $in_fh, '<:raw', $in_qfn)
or die("Unable to open \"$in_qfn\": $!\n");
open(my $out_fh, '>', $out_qfn)
or die("Unable to open \"$out_qfn\": $!\n");
while (1) {
defined( my $rv = sysread($in_fh, my $buf, BLOCK_SIZE) )
or die("Unable to read from \"$in_qfn\": $!\n");
last if !$rv;
print($fh_out unpack("H*", $buf))
or die("Unable to write to \"$out_qfn\": $!\n");
}
close($fh_in);
close($fh_out)
or die("Unable to write to \"$out_qfn\": $!\n");
The above addressed a lot of other issues in your program: 上面的内容解决了程序中的许多其他问题:
unpack H*
handles strings of any length unpack H*
处理任意长度的字符串时, unpack H*
分割输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.