YouHaveaBigEgo
YouHaveaBigEgo

Reputation: 220

Printing a binary buffer in readable Hex format instead of ASCII format

I have a binary buffer $data which has some hex data and if I print it, I'd get this :

$VAR1 = '☺, ?♥☻♦\' N v ►☻ ☻ ◄☻   ↕♥    ‼♥    ¶♥    §* ☺♥☺♥☺@☺ ☺☺☺♠☺♠☺ ☺♦ ☺♀         ☺☻ ☺3

which obviously makes no sense to me. But it would be very helpful if I can print it as :

8F 00 8F 13 D0 21 A5 25 A3 DA CA 00 01 82 00 80 03 02 04 27 00 4E 00 76 

instead.

I tried using sprintf("%x", $data), but that doesn't help.

Can someone help me?

Thanks!

Upvotes: 1

Views: 4095

Answers (2)

ikegami
ikegami

Reputation: 386676

If you're not too fussy on the format,

sprintf("%v02X", $bytes)

will give you

8F.00.8F.13....

If you really want

8F 00 8F 13 ...

Then the following are some options:

sprintf("%v02X", $bytes) =~ s/\./ /rg

join ' ', map { sprintf("%02X", ord($_)) } split(//, $bytes)

join ' ', unpack '(H2)*', $bytes

Upvotes: 6

Miller
Miller

Reputation: 35208

Use the ord function:

$VAR1 = '☺, ?♥☻♦\' N v ►☻ ☻ ◄☻   ↕♥    ‼♥    ¶♥    §* ☺♥☺♥☺@☺ ☺☺☺♠☺♠☺ ☺♦ ☺♀         ☺☻ ☺3';

print join ' ', map {sprintf("%x", ord)} split //, $VAR1;

Outputs:

e2 98 ba 2c 20 3f e2 99 a5 e2 98 bb e2 99 a6 27 20 4e 20 76 20 e2 96 ba e2 98 bb 20 e2 98 bb 20 e2 97 84 e2 98 bb 20 20 20 e2 86 95 e2 99 a5 20 20 20 20 e2 80 bc e2 99 a5 20 20 20 20 c2 b6 e2 99 a5 20 20 20 20 c2 a7 2a 20 e2 98 ba e2 99 a5 e2 98 ba e2 99 a5 e2 98 ba 40 e2 98 ba 20 e2 98 ba e2 98 ba e2 98 ba e2 99 a0 e2 98 ba e2 99 a0 e2 98 ba 20 e2 98 ba e2 99 a6 20 e2 98 ba e2 99 80 20 20 20 20 20 20 20 20 20 e2 98 ba e2 98 bb 20 e2 98 ba 33

Note: if your data is utf8, then you'll need to specify it as such:

263a 2c 20 3f 2665 263b 2666 27 20 4e 20 76 20 25ba 263b 20 263b 20 25c4 263b 20 20 20 2195 2665 20 20 20 20 203c 2665 20 20 20 20 b6 2665 20 20 20 20 a7 2a 20 263a 2665 263a 2665 263a 40 263a 20 263a 263a 263a 2660 263a 2660 263a 20 263a 2666 20 263a 2640 20 20 20 20 20 20 20 20 20 263a 263b 20 263a 33

Upvotes: 1

Related Questions