views:

20

answers:

1

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?

+1  A: 

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);
Marc B