0

I need to convert the bin file to a string in PHP in the same way as the Linux program does.

In linux: xxd -g 1 data.bin and output: 0000000: 02 50 45 10 02 06 54 62 43 20 05 20 11 07 21 12 .PE...TbC . ..!.

In PHP, I tried to use the bin2hex function, but i get only the digits 02 50 45 10 02 06 54 62 43 20 05 20 11 07 21 12. I also need an offset and textual representation.

The offset is the line number, the first digits and a colon (0000000:) in the string I entered above. This is actually not a problem, because I can write code that calculates this, but the bigger problem is with textual representation (.PE...TbC . ..!.).

Someone can help? What functions could I use for this?

Krystian
  • 47
  • 7
  • 1
    What do you mean by "offset"? Why not write code that calculates this offset? – Nico Haase Aug 10 '21 at 14:45
  • @NicoHaase The offset is the line number, the first digits and a colon in the string I entered. This is actually not a problem, but the bigger problem is with textual representation. – Krystian Aug 10 '21 at 14:54
  • Then please add all details to your question by editing it – Nico Haase Aug 10 '21 at 15:04
  • Does this answer your question? [How to remove all non printable characters in a string?](https://stackoverflow.com/questions/1176904/how-to-remove-all-non-printable-characters-in-a-string) – Matt Raines Aug 10 '21 at 15:27

1 Answers1

0

You can use a regular expression to replace non-printable characters with a . (or whatever character you choose).

$data = hex2bin('02504510020654624320052011072112');
$text_representation = preg_replace('/[^[:print:]]/', '.', $data);
var_dump($text_representation);
Matt Raines
  • 4,149
  • 8
  • 31
  • 34