2

Support I have some hex raw data printed using c code with format such as “%02X”.
so they look like :

\x00\x20\x00\x10\xfd\x02\x10\x00\x00\x00\x00\x20\xff\x02\x10\x00\x00\x00\x00\x00 \x05\x00\x011\x00\x01\x00\n\x00\x0240

I want to decode them following some format like:
The first two Byte hex “\x00\x20” should be decoded to a ushort:
The following two B hex “\x00\x10” should be decoded to a ushort:
The following 8B hex “\xfd\x02\x10\x00\x00\x00\x00\x20” should be coded to a 64 bit.
The following 8B hex “\xff\x02\x10\x00\x00\x00\x00`\x00” should be coded to a 64 bit;
The following 3 Byte Hex should be decoded to 3 char.
....

How do I implement the decoding in perl
(BTW I do not understand why there are backslash between each hex, is it how hex should be printed out)?

2 Answers 2

1

s{\\x(..)}{chr hex $1}eg; for single bytes. or just unpack("v", "\x00\x20"); (see unpack function for details).

Sign up to request clarification or add additional context in comments.

3 Comments

#!/usr/bin/perl -w $_ = "\x61\x62"; s{\\x(..)}{chr hex $1}eg; print "approach1: $_\n"; $str2 = unpack("v", "\x61\x62"); print "approach2: $str2\n";
the answer is:bash-3.00# ./hex2str.pl approach1: ab approach2: 25185
Indeed. And it wholly depends on what you want which approach you use. One day you say ushort (short of Perl not having "shorts" - "\x61\x62" is a string, "ab" is another string, and 25185 is a number, usually with a capacity of int), so use approach 2; the other you say "hex2str", so use appoach 1.
0
  1. Decode the data:
    • s/\\x(..)/chr hex $1/eg/;
    • Better still, assuming you have control over the C code that generates the input, get it to output binary data in the first place and avoid this step entirely.
  2. Use unpack to decode the components.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.