gpt4 book ai didi

c# - 如何从 C# 的 BinaryWriter 创建的二进制文件中读取 php 中的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:24:32 25 4
gpt4 key购买 nike

我的 C# 代码正在使用 BinaryWriter 编写这样的二进制文件:

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 中,我正在尝试阅读它。现在我正在这样做:

$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 format 中为字符串加上可变大小的值作为前缀.我怎样才能从这个长度的二进制文件中读取,以便我可以读取字符串的正确长度?我想我会用 Google 和搜索 Stack Overflow 找到一些东西,但我没有运气。我尝试了 unpack 变量但没有成功。

最佳答案

好吧,我的同事为我写了一个方法来做这件事,就在这里:

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);
}

像这样简单地调用:

$myfile = fopen($filename, "r+") or die("Unable to open file!");
$string = ReadString($myfile);

关于c# - 如何从 C# 的 BinaryWriter 创建的二进制文件中读取 php 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com