php pack:数据类型问题和我的结果验证

php pack: problems with data types and verification of my results

我是 PHP 初学者,我的任务是构建稍后将通过 UDP 发送到设备的命令。 运行: OSX, PHP 5.5.3.8 要创建二进制数据,我使用 "pack"。这是我的代码示例:

<?php
$in_1 = 0x3100;
$in_2 = 0031;
echo "Inputs: " . $in_1 . "\t" . $in_2;
$bin = pack("v*", $in_1, $in_2);
echo "\nlength: ". strlen($bin);
printf ("\npacked result: %x \n",$bin);
printf("HEX result %h\n", $bin);
file_put_contents("ausgabe.log", $bin, FILE_APPEND);
?>

我终端的输出是:

Inputs: 12544   25
length: 4
packed result: 0 
HEX result 

我想知道 $in_2 的数字 25。 如果我将 0x0031 分配给 $in_2,结果是 49。 这里有什么问题吗?

顺便说一句:我的最终目标是在这样的方案中构建恰好 12 字节的二进制命令(十进制值作为每行中的注释):

function set_routing_item ($in_ch, $out_ch, $on_off, $seq)
{
    $command = toggle_two_bytes(37);    // 37 --> 0x2500
    $status = 0x0000;                   // 0 --> 0x0000
    $pos = 4;                           // 4= route item
    $channel_1 = $in_ch;                // 3
    $channel_2 = $out_ch;               // 6
    $preset_no = 0xff;                  // 255
    $value = $on_off;                   // 33145
    $seq = $seq;                        // 35
    // implement building of command using pack here
}

这种情况下的结果(十六进制)应如下所示:25 00 00 00 04 03 06 FF 79 81 23 00

谢谢!

抱歉我的回答格式错误。 这是请求的代码:

// toggle higher and lower byte of a two-byte short variable
function toggle_two_bytes ($two_bytes)`

{
    $two_bytes = $two_bytes & 0xffff; // limit size to 2 Bytes
    $high = ($two_bytes << 8);          // bit shift
    $low = ($two_bytes >> 8);
    $ret = ($high | $low);              // OR
    $ret = $ret & 0xffff;               // limit (again) to two bytes
    return ($ret);
}

我发现有了 pack('v',...) 就不再需要了。

我想到了这个,但不是最好的方法,适当的按位运算会更快。

我正在使用 sprintf%x 格式说明符,它将值转换为十六进制值。

Each conversion specification consists of a percent sign (%)

你会看到我使用 %02x%04x

  • 0 - 用零填充数字
  • 24 - 宽度,要打印的最小字符数。
  • x - 十六进制说明符,使用 X 表示大写。

代码:

<?php
function toggle_two_bytes ($two_bytes)
{
    $two_bytes = $two_bytes & 0xffff;   // limit size to 2 Bytes
    $high = ($two_bytes << 8);          // bit shift
    $low = ($two_bytes >> 8);
    $ret = ($high | $low);              // OR
    $ret = $ret & 0xffff;               // limit (again) to two bytes
    return ($ret);
}


function set_routing_item ($in_ch, $out_ch, $on_off, $seq)
{
    $str  = '';
    $command = toggle_two_bytes(37);
    $str .= sprintf('%04X', $command);

    $status = 0x0000;
    $str .= sprintf('%04X', $status);

    $pos = 4;
    $str .= sprintf('%02X', $pos);

    $str .= sprintf('%02X', $in_ch);

    $str .= sprintf('%02X', $out_ch);

    $preset_no = 0xFF;
    $str .= sprintf('%02X', $preset_no);

    $value = toggle_two_bytes($on_off);
    $str .= sprintf('%04X', $value);

    $seq = toggle_two_bytes($seq);
    $str .= sprintf('%04X', $seq);

    for ($i = 0; $i < strlen($str) - 1; $i += 2) {
      echo $str[$i] . $str[$i+1] . ' ';
    }
}

echo set_routing_item(3, 6, 33145, 35) . PHP_EOL;

输出:

25 00 00 00 04 03 06 FF 79 81 23 00

演示:https://eval.in/793695