[英]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
謝謝!
我想出了這個,但這不是最好的方法,適當的按位操作會更快。
我正在使用帶有%x
格式說明符的sprintf
,它將值轉換為十六進制值。
每個轉換規范都包含一個百分號(%)
您將看到我使用%02x
和%04x
0
- 左鍵用零填充數字 2
或4
- 寬度,即要打印的最小字符數。 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
抱歉我的格式錯誤答案。 這是請求的代碼:
// 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',...),這已經不再需要了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.