首页 > 解决方案 > Objective C uint8_t PHP 等价物

问题描述

我正在将脚本中的小Objective C代码PHP转换为将整数数组转换为二进制文件。

目标 C 代码

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

这是我的PHP 代码


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

?>

PHP 生成的 Binary File 与 Obj-C 生成的文件有点不同。我想我需要在 PHP 中进行字符编码。

你能指导我什么是uint8_tPHP中的等效编码吗?

标签: phpobjective-ctypesbinaryfiles

解决方案


找到了解决方案。

PHPpack()通过采用格式参数将数据打包成二进制字符串。

正如我"I" -> unsigned integerpack()给出 32 位编码的结果中使用的那样。然后trim()删除多余的空格,生成的数据变为 8 位以下的编码。

我试图通过chr()在 PHP 中使用从数字生成单字节字符串

echo chr($arr[$i]);

它对我有用:)。


推荐阅读