如何使用Perl将十六进制字符串转换为字节数组

时间:2012-07-23 07:37:59

标签: perl perl-data-structures

我想转换十六进制字符串说

[0] = 0x4A,[1] = 0x06,[2] = 0x0E,[3] = 0xF1,[4] = 0x95,[5] = 0x3B,[6] = 0xD9,[7] = 0x90 ,[8] = 0x5B,[9] = 0x63,[10] = 0xCA,[11] = 0xA9,[12] = 0x37,[13] = 0xC8,[14] = 0x8D,[15] = 0xDA,[ 16] = 0x64,[17] = 0x82,[18] = 0x99,[19] = 0x9F,[20] = 0xE1,[21] = 0x1A,[22] = 0x3B,[23] = 0xB6,[24] = 0xFC,[25] = 0x68,[26] = 0xC0,[27] = 0xD2,[28] = 0x7B,[29] = 0x01,[30] = 0x21,[31] = 0xDD}

进入字节数组

4A060EF1953BD9905B63CAA937C88DDA6482999FE11A3BB6FC68C0D27B0121DD

反向,有人可以建议吗?

2 个答案:

答案 0 :(得分:2)

$str = '[0] =0x4A ,[1] =0x06 ,[2] =0x0E ,[3] =0xF1 ,[4] =0x95 ,[5] =0x3B ,[6] =0xD9 ,[7] =0x90 ,[8] =0x5B ,[9] =0x63 ,[10]=0xCA ,[11]=0xA9 ,[12]=0x37 ,[13]=0xC8 ,[14]=0x8D ,[15]=0xDA ,[16]=0x64 ,[17]=0x82 ,[18]=0x99 ,[19]=0x9F ,[20]=0xE1 ,[21]=0x1A ,[22]=0x3B ,[23]=0xB6 ,[24]=0xFC ,[25]=0x68 ,[26]=0xC0 ,[27]=0xD2 ,[28]=0x7B ,[29]=0x01 ,[30]=0x21 ,[31]=0xDD';
$str =~ s/\s*,?\[.*?\]\s*=0x//gi;
print $str, "\n";
$str =~ s/([0-9A-F]{2})/0x$1, /gi;
print $str, "\n";

答案 1 :(得分:1)

取决于字节数组的含义:

my $dump = '[0] =0x4A ...';
my $bytes = pack 'H*', join '', $dump =~ /0x(..)/sg;

反之亦然:

my $bytes = "\x4A\06...";
my @bytes = unpack 'C*', $bytes;
my $dump = join ', ', map sprintf("[%d] = 0x%02X", $_, $bytes[$_]), 0..$#bytes;

或者:

my $dump = '[0] =0x4A ...';
my @bytes = map hex, $dump =~ /0x(..)/sg;

反之亦然:

my @bytes = (0x4A, 0x06, ...);
my $dump = join ', ', map sprintf("[%d] = 0x%02X", $_, $bytes[$_]), 0..$#bytes;