简体   繁体   English

PHP Pack二进制数据

[英]PHP pack binary data

This is with regard to data sent over a socket to a C application residing on a remote POS system. 这是关于通过套接字发送到远程POS系统上的C应用程序的数据。

Binary data is sent from a php application, in the C app packet structure there is 64bytes stored for a string eg a product name. 二进制数据是从php应用程序发送的,在C app数据包结构中,为字符串(例如产品名称)存储了64个字节。

Now when I send the product name across network through php sockets, I use pack to convert data to binary 现在,当我通过php套接字通过网络发送产品名称时,我使用pack将数据转换为二进制

$value = 'product name' 
$qty = 2;
$len = strlen($value);
$output = '';
for($i=0; $i<$len; $i++) {
        $output .= pack('c', ord(substr($value, $i, 1))).pack('c',$qty) 
}

When the data is received by the C application the string contains a lot of garbage data, including numbers and special characters. 当C应用程序接收到数据时,字符串包含大量垃圾数据,包括数字和特殊字符。

Which of the pack options i have to use to pack the product name into a 64byte binary string that will be interpreted by the C application in the correct format. 我必须使用哪个打包选项将产品名称打包为64字节的二进制字符串,C应用程序将以正确的格式对其进行解释。

Sending binary data through network sockets also may create troubles with byte ordering (Endianess), you might wanna check out if the byte ordering is the same on both systems. 通过网络套接字发送二进制数据也可能会导致字节顺序(Endianess)出现问题,您可能想检查一下两个系统上的字节顺序是否相同。 http://en.wikipedia.org/wiki/Endianness http://en.wikipedia.org/wiki/Endianness

Your loop to build $output produces a string like "p\\x02r\\x02o\\x02d\\x02u\\x02c\\x02t\\x02 \\x02n\\x02a\\x02m\\x02e\\x02" 构建$output循环将生成一个字符串,例如"p\\x02r\\x02o\\x02d\\x02u\\x02c\\x02t\\x02 \\x02n\\x02a\\x02m\\x02e\\x02"

If your C program expects something like "product name\\0\\x02" , then the loop should be: 如果您的C程序期望使用类似于"product name\\0\\x02" ,则循环应为:

$output = '';
for($i=0; $i<$len; $i++) {
        $output .= pack('c', ord(substr($value, $i, 1))); 
}
$output .= pack('c',0).pack('c',$qty);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM