生成具有给定结构的二进制文件

发布于 2024-09-16 18:26:39 字数 435 浏览 8 评论 0原文

我有一个使用二进制格式样式配置的设备,我必须即时生成该文件。

文件结构必须包含多个配置设置(每个参数 1 个),每种形式如下:

  • 类型
  • 长度

其中:

  • 类型:是定义参数的单八位字节标识符
  • 长度:是包含值字段长度的单八位字节以八位位组为单位(不包括类型和长度字段)
  • 值:从 1 到 254 个八位位组,包含参数的特定值

我有一个相应的表

 Type_code[int] => { Type_length[int] => Value[int/string/hex/etc.] }

如何将该表解析为该二进制格式? 第二种方法,如何解析该二进制文件,将其转换为 php 数组格式?

I have a device witch use binary format style config, and i have to generate that files on-the-fly.

File structure must consist of a number of configuration settings (1 per parameter) each of the form:

  • Type
  • Length
  • Value

where:

  • Type: is a single-octet identifier which defines the parameter
  • Length: is a single octet containing the length of the value field in octets (not including type and length fields)
  • Value: is from one to 254 octets containing the specific value for the parameter

I have a corresponding table

 Type_code[int] => { Type_length[int] => Value[int/string/hex/etc.] }

How to parse that table to that binary format?
And, second way, how to parse that binary file, to php array format back?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

思慕 2024-09-23 18:26:39

/解包可以在各种二进制/十六进制/八进制/字符串格式之间进行转换的函数。读取文件的一大块,通过解包提取必要的位,然后从那里开始工作。

$fh = fopen('data.txt', 'rb'); // b for binary-safe

// read 2 bytes, extract code/length, then read $length more bytes to get $value
while(($data = fread($fh, 2)) !== EOF)) { 
    list($code, $length) = unpack('CC', $data);
    $data = fread($fh, $length);

    // do stuff
}
fclose($fh);

There's the pack/unpack functions that can translate between various binary/hex/octal/string formats. Read a chunk of the file, extract necessary bits with unpack, and work from there.

$fh = fopen('data.txt', 'rb'); // b for binary-safe

// read 2 bytes, extract code/length, then read $length more bytes to get $value
while(($data = fread($fh, 2)) !== EOF)) { 
    list($code, $length) = unpack('CC', $data);
    $data = fread($fh, $length);

    // do stuff
}
fclose($fh);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文