开发者

perl: How to decode hex data to integer, string?

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)?


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


  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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜