简体   繁体   中英

PHP pack binary data

This is with regard to data sent over a socket to a C application residing on a remote POS system.

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.

Now when I send the product name across network through php sockets, I use pack to convert data to binary

$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.

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.

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. 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"

If your C program expects something like "product name\\0\\x02" , then the loop should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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