1

To create a new file ,to input just one enter key and save it as test.txt.
There is only one '\n' in the test.txt.
To display the file with command:

 xxd  -b ./test.txt
 0000000: 00001010   

Now i want to do the same job with php.

<?php
function  parse($target){
    $file_handle = fopen($target, "rb");
    while (!feof($file_handle)) {
       $byte = fread($file_handle,1);
       echo  base_convert(ord($byte),10,2);
    }   
    fclose($file_handle );
} 
parse('test.txt');  
?>

The result is 10100 ,how to fix my php code to get the such right answer 00001010 as xxd -b ./test.txt ?
Think to Pyton's code.

<?php
function  parse($target){
    $file_handle = fopen($target, "rb");
    while (!feof($file_handle)) {
       $byte = fread($file_handle,1);
       echo  sprintf("%08s ",base_convert(ord($byte), 10, 2));
    }   
    fclose($file_handle );
} 
$target='test.txt';  
echo filesize($target);
parse($target);
?>

The filesize is 1,but result is 00001010 00000000 ,how to make it to be exactly 00001010?

1 Answer 1

1
<?php
function  parse($target){
    $file_handle = fopen($target, "rb");
    $filesize = filesize($target);    
    while (!feof($file_handle)) {
        $byte = fread($file_handle, 1);
        echo sprintf("%'08b", ord($byte));
        if(ftell($file_handle) == $filesize) {
            break;
        }
    }
    fclose($file_handle );
}
parse('test.txt');

Output:

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

1 Comment

The filesize is 1,but result is 00001010 00000000 ,how to make it to be exactly 00001010?

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.