How to read a string in php from a binary file created from c#'s BinaryWriter
我的c#代码正在使用BinaryWriter编写这样的二进制文件:
1 2 3 4 5 | writer.Write(Encoding.ASCII.GetBytes("MAGIC")); //5 ascii characters writer.Write(version.ToString()); // could be any System.Version.ToString():"1.2.3.4" or"1.2" or"1.1.1.11", etc writer.Write(hash); // byte[20] writer.Write(signature); // byte[256] // etc. |
在PHP中我试图阅读它。 现在我这样做:
1 2 3 4 5 6 7 8 9 | $myfile = fopen("private/test.txt","r+") or die("Unable to open file!"); echo fread($myfile,5); // read/print the magic file identifier // problem start $versionLength = ?????; //problem end $versionString = fread($myfile,$versionLength); ..... |
据我所知,BinaryWriter将为LEB128格式的字符串添加一个可变大小的值作为前缀。 如何从二进制文件中读取这个长度,以便我可以读取字符串的正确长度? 我想我会在谷歌找到一些东西并搜索Stack Overflow,但我没有运气。 我尝试了unpack变量,但没有成功。
好吧,我的同事写了一个方法为我做这个,这里是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | function ReadVarInt($file) { $val = 0; $bits = 0; while ($bits != 35) { $n = ord(fread($file, 1)); if ($n === FALSE) return FALSE; $val |= ($n & 0x7F) << $bits; $bits += 7; if (!($n & 0x80)) return $val; } //error"Too many bytes in what should have been a 7 bit encoded Int32."; return FALSE; } function ReadString($file) { $len = ReadVarInt($file); if ($len === FALSE) return FALSE; if ($len < 0) { //error"Negative String Length"; return FALSE; } return fread($file, $len); } |
只需这样打电话:
1 2 | $myfile = fopen($filename,"r+") or die("Unable to open file!"); $string = ReadString($myfile); |