user285686
user285686

Reputation: 195

How To Convert a Hexadecimal String into Byte Array using Perl

I Would Like to convert an Hexadecimal String Say

[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 }

into byte array as

4A060EF1953BD9905B63CAA937C88DDA6482999FE11A3BB6FC68C0D27B0121DD

and vice -versa, could somebody please suggest?

Upvotes: 0

Views: 2511

Answers (2)

ikegami
ikegami

Reputation: 385779

Depending on what you mean by byte array:

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

vice-versa:

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

Or:

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

vice-versa:

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

Upvotes: 1

cdtits
cdtits

Reputation: 1128

$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";

Upvotes: 2

Related Questions