I am converting small Objective C
code in PHP
script to convert integer array to Binary File.
Objective C code
typedef struct {
uint8_t fj1;
uint8_t fj2;
uint8_t sr1;
uint8_t sr2;
uint8_t zh1;
uint8_t zh2;
uint8_t as1;
uint8_t as2;
uint8_t mg1;
uint8_t mg2;
uint8_t is1;
uint8_t is2;
} struct_pt;
struct_pt g_p_t[366]= {
1, 29, 2, 49, 8, 15, 11, 16, 13, 37, 14, 52,
1, 29, 2, 49, 8, 16, 11, 17, 13, 37, 14, 53,
1, 29, 2, 50, 8, 16, 11, 18, 13, 38, 14, 53,
…………..
}
const char *filePath = "/Users/usr/path/to/folder/filename.bin”;
FILE *file = fopen(filePath, "wb");
if (file != NULL) {
fwrite(g_p_t, sizeof(uint8_t), sizeof(g_p_t), file);
}
And here is my PHP Code
// array of 366 rows
$arr = [1, 29, 2, 49, 8, 15, 11, 16, 13, 37, 14, 52,
1, 29, 2, 49, 8, 16, 11, 17, 13, 37, 14, 53,
1, 29, 2, 50, 8, 16, 11, 18, 13, 38, 14, 53,
……..
];
header("Content-Disposition: attachment; filename=\”file.bin\"");
header("Pragma: no-cache");
header("Expires: 0");
for ($i=0; $i < count($arr); $i++) {
echo trim(pack("I", $arr[$i]));
}
fclose($out);
?>
The Binary File generated by PHP is a bit different from the file generated by Obj-C. I suppose I need to do character encoding in PHP.
Can you please guide me what is the equivalent encoding of uint8_t
in PHP?
Found the solution.
PHP pack()
packs the data into Binary string by taking format parameter.
As I am using "I" -> unsigned integer
in pack()
give result of 32bit encoding. Then trim()
removes extra spaces and resulting data become encoding of below 8bit.
I've tried to generate a single-byte string from a number by using chr()
in PHP
echo chr($arr[$i]);
And it worked for me :).