将ASCII TEXT转换为二进制

问题描述 投票:-1回答:1

我必须将ASCII文件转换为二进制文件。 ASCII文件包含ASCII格式的十二位十六进制数字。对于123456789ABC的输入字符串,我需要输出0x12 \ 0x34 \ 0x56 \ 0x78 \ 0x9a \ 0xbc的六字节。这是有效的解决方案。谢谢您的帮助。

my $filename = 'Hub_Device_ID.txt';
my $outfile= 'Hub_Device_ID.bin';
open(my $fh, '<:encoding(UTF-8)', $filename)
         or die "Could not open file '$filename' $!";
open(my $of, '>:raw', $outfile)
         or die "Could not open file '$outfile' $!";
  binmode($of);

  while (my $row = <$fh>){

    chomp $row;
    print "Chomped row\n";
    print $row, "\n";


    my $bytes = pack 'H*', $row;
    print $bytes, "\n";
    print $of $bytes;


    close $of;
    close $fh;

    print "Done\n";

}

perl hex ascii
1个回答
-1
投票

我相信你想转换

my $hex = "0123456789aBcDeF";

my $bytes = "\x01\x23\x45\x67\x89\xAB\xCD\xEF";

要做到这一点,只需使用

my $bytes = pack 'H*', $hex;
© www.soinside.com 2019 - 2024. All rights reserved.