在PHP中编辑的六角形字符串数组

时间:2018-03-19 21:27:25

标签: php arrays hex rgb checksum

我正在尝试从我的网站上获取RGB值到平板电脑。平板电脑仅接受SICP命令。 目前我正在使用netcat建立这样的连接:

$cmd = 'echo -n -e "\x09\x01\x00\xf3\x01\xff\x80\x00'.$checksum.'" | nc '.$ip.' '.$port;
                shell_exec($cmd);
                echo $cmd;

这适用于平板电脑,但我仍然无法为3个RGB值制作变量,因为我的校验和计算器需要hexa格式。 我可以在PHP中创建六进制数组(" hexstrcomp"),其中最后4个值是RGB和校验和。

$hexshowndec = array("09","01","00","f3", "01", "ff", "80", "00", "00");     
$hexstrcomp = array("\x09","\x01","\x00","\xf3","\x01","\xff","\x80","\x00","\x00");
                for ($i = 0; $i < 8; $i++)  // 8 for message length before checksum
                {
                    $byte = $hexstrcomp[$i];
                    $hexstrcomp[8] = $hexstrcomp[8] ^ ord($byte);
                    echo "Current checksum: " . sprintf("%02x", $hexstrcomp[8]) . "<br>"; // 0x23
                }
                echo "Checksum: " . sprintf("%02x", $hexstrcomp[8]);

                $cmd = 'echo -n -e "\x' . $hexshowndec[0]
                        . '\x' . $hexshowndec[1]                             
                        . '\x' . $hexshowndec[2] 
                        . '\x' . $hexshowndec[3] 
                        . '\x' . $hexshowndec[4] 
                        . '\x' . $hexshowndec[5] 
                        . '\x' . $hexshowndec[6] 
                        . '\x' . $hexshowndec[7] 
                        . '\x' . sprintf("%02x", $hexstrcomp[8])
                        . '" | nc '.$ip.' '.$port;
                shell_exec($cmd);
                echo "<p>Orange!</p>";

我怎样才能更改hexstrcomp [5]的值,所以我仍然可以成功使用我的校验和?尝试以下导致校验和失败:

$hexshowndec[6] = sprintf("%02x", $hexstrcomp[6]); //gets this done
$hexstrcomp[6] = "\x00";    // works, but need variable for 00 part
$hexstrcomp[6] = "\x{$hexshowndec[6]}";    // fails
$hexstrcomp[6] = "\x" . $hexshowndec[6];    // fails

1 个答案:

答案 0 :(得分:1)

$hexshowndec[6]转换为带有hexdec()的十进制,然后将其转换为一个字符(在您的情况下为原始字节)chr()

$hexstrcomp[6] = chr( hexdec( $hexshowndec[6] ) );

实际上,您可以使用相同的方法和foreach循环从$hexstrcomp以编程方式创建$hexshowndec

$hexshowndec = array("09", "01", "00", "f3", "01", "ff", "80", "00", "00"); 
$hexstrcomp = array();
foreach( $hexshowndec as $hsd ) {
    $hexstrcomp[] = chr( hexdec ( $hsd ) );
}

...或者使用更短的在线人员:

$hexshowndec = array("09", "01", "00", "f3", "01", "ff", "80", "00", "00"); 
$hexstrcomp = str_split( pack( "H*", implode( '', $hexshowndec ) ) );

您的任意长度输入的脚本:

$hexshowndec = array( "09", "01", "00", "f3", "01", "ff", "80", "00", "00");     
$hexstrcomp = str_split( pack( "H*", implode( '', $hexshowndec ) ) );

// The last byte is for checksum and initially set to 0x00
$n = count( $hexshowndec ) - 1;

for( $i = 0; $i < $n; $i++ )
{
    $byte = $hexstrcomp[ $i ];
    $hexstrcomp[ $n ] = $hexstrcomp[ $n ] ^ ord( $byte );
}

$cmd = 'echo -n -e "';
for( $i = 0; $i < $n; $i++ )
{
    $cmd .= '\x' . $hexshowndec[ $i ];
}

$cmd .= '\x' . sprintf( "%02x", $hexstrcomp[ $n ] );  
$cmd .= '" | nc '.$ip.' '.$port;

shell_exec( $cmd );