开发者

How do I use the PHP Pack function to pack an integer into a byte array?

The following C# code is used in a service I have inherited, to convert a small integer into 3 bytes so that it can be sent over a socket.

int i = 12345;
byte[] data = new byte[] { (byte)i, (byte)(i >> 8), (byte)(i >> 16)};
var result = data[0] + (data[1] << 8) + (data[2] << 16);

Using PHP I am opening a socket to the service. The communications protocol is written at byte level, so I have to send bytes over the PHP socket.

I have determined that to do this, I have to use the pack function.

    <?php
    $binarydata = pack("CCCC", 0xFF, 0x00, 0x00, 0x00);
socket_write($sk, $binarydata, $binarydataLen);
    ?>

The first byte tells the server what the client wants to do, and in this case the following 3 bytes must represent an integer conforming to the formulae shown in the c# implementation above.

The problem that I have, is no matter what I try, I cannot create the 3 byte array from an integer that matches the c# implementation.

I would really appreachiate and vote up any one that can help me solve this, for an experienced PHP developer I think they might know the right syntax to use.

Thank you. Christian

Edit: Here is prototype

//The Client
error_reporting(E_ALL);

$address = "127.0.0.1";
$port = <removed>;

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "socket successfully created.\n";
}

echo "Attempting to connect to '$address' on port '$port'...";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "开发者_开发问答successfully connected to $address.\n";
}

    $value = 17;
    $binarydata = pack("c*", 0xFE, $value & 0x000F, ($value>>8) & 0x000F, ($value>>16) & 0x000F);
    socket_write($socket, $binarydata, 4);
    $input = socket_read($socket, 2048);
    echo "Response from server is: $input\n";


    sleep(5);

echo "Closing socket...";
socket_close($socket);

The expected output is "FE 11 00 00" (11 being 17)

Unfortunately it is sending "FE 01 00 00" according to the logs :-(

The server responds in ASCII so I just need to get this number right as it will change dynamically.

EDIT: THANKS ALL, ITS WORKING! xD

$binarydata = pack("cc*", 0xFE, $value, ($value>>8), ($value>>16));


the format "nvc*" is not correct. It will generate 6 bytes. You should do this:

    $binarydata = pack("c*", $value & 0x000F, ($value>>8) & 0x000F, ($value>>16) & 0x000F);


As you're writing packing bytes, shouldn't the function be used like this?

$binarydata = pack("CCCC", 0xFF, 0x00, 0x00, 0x00);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜