PHP reads the file as an array of bytes

I have a file written using the JAVA program, which has an array of integers written as binary. I did a for loop on this array and write it using this method

 public static void writeInt(OutputStream out, int v) throws IOException { out.write((v >>> 24) & 0xFF); out.write((v >>> 16) & 0xFF); out.write((v >>> 8) & 0xFF); out.write((v >>> 0) & 0xFF); } 

I ask how to read this file in PHP .

+6
source share
2 answers

I believe the code you are looking for is:

 $byteArray = unpack("N*",file_get_contents($filename)); 

UPDATE: Working code provided by OP

 $filename = "myFile.sav"; $handle = fopen($filename, "rb"); $fsize = filesize($filename); $contents = fread($handle, $fsize); $byteArray = unpack("N*",$contents); print_r($byteArray); for($n = 0; $n < 16; $n++) { echo $byteArray [$n].'<br/>'; } 
+10
source

You should read the file as a string, and then use the decompression to parse it. In this case, you saved a 32-bit integer in byte order of a large byte, so use:

 $out = unpack("N", $in); 

The format codes are described here: http://www.php.net/manual/en/function.pack.php

+4
source

Source: https://habr.com/ru/post/950686/


All Articles