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?
My Answer:
You can achieve the same output as the xxd command in PHP by using the following code:
php
$filename = 'data.bin';
$handle = fopen($filename, 'rb');
$offset = 0;
while (!feof($handle)) {
$data = fread($handle, 16);
$hex = bin2hex($data);
$ascii = '';
for ($i = 0; $i < strlen($data); $i++) {
$ascii .= (ord($data[$i]) >= 32 && ord($data[$i]) <= 126) ? $data[$i] : '.';
}
printf("%08x: %-47s %s\n", $offset, strtoupper(chunk_split($hex, 2, ' ')), $ascii);
$offset += 16;
}
fclose($handle);
This code will read the binary file `data.bin` and output the hexadecimal representation, offset, and textual representation in the same format as the xxd command in Linux.
Rate this post
3 of 5 based on 7093 votesComments