开发者

Generate binary file with given structure

开发者 https://www.devze.com 2023-01-13 14:58 出处:网络
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 for

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 typ开发者_StackOverflow社区e 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消