从php

时间:2017-05-19 21:52:13

标签: php hex

如何从这个字符串"c0dbdc000081aa02000000000001c0"中获取7个变量,定义每个变量的长度,有时候它会在零中出现空白。

定义从字符串中获取数据:

0xc0->[SLIP Start char:C0]
0xdb,0xdc[C0]->Flag|Version:c,0
0x00->Reserved:0
0x00,0x81->Packet length:129
0xaa,0x02->Packet command:AA02[hex]
0x00,0x00->CRC check:0[hex]
0x00,0x00,0x00,0x01->Serial number:1
0xc0->[SLIP End char:C0]

示例:这是3个具有相同数据的字符串,但其中2个在“数据包长度”值中较短,它们没有2个前导零。 (添加了一些间距以显示缺失的零)

"c0000000  9aaa02000000000029c0"
"c0000000  85aa0200000000000ac0"
"c0dbdc000081aa02000000000001c0"

我已经使用了最后一个代码,但是第一个代码因为缺少零而变得混乱。关于如何管理这个的任何想法?

$inputSample = "C0DBDC000081AA02000000000001C0";
$header = array(
    "start" => 2,
    "flagVersion" => 4,
    "reserved" => 2,
    "packetLenght" => 4,
    "packetCommand" => 4,
    "CRCcheck" => 4,
    "serialNumber" => 8,
    "end" => 2
);
print_r(ParseIrregularString($inputSample, $header));

function ParseIrregularString($string, $lengths) {
    $parts = array();

    foreach ($lengths as $StringKey => $position) {
        $parts[$StringKey] = substr($string, 0, $position);
        $string = substr($string, $position);
    }

    return $parts;
}

结果良好“C0DBDC000081AA02000000000001C0”

Array
(
    [start] => C0
    [flagVersion] => DBDC
    [reserved] => 00
    [packetLenght] => 0081
    [packetCommand] => AA02
    [CRCcheck] => 0000
    [serialNumber] => 00000001,
    [end] => C0
)

错误结果“c00000009aaa02000000000029c0”

Array
(
    [start] => c0
    [flagVersion] => 0000
    [reserved] => 00
    [packetLenght] => 9aaa
    [packetCommand] => 0200
    [CRCcheck] => 0000
    [serialNumber] => 000029c0
    [end] => 
)

0 个答案:

没有答案