Pergunta

I have a string in the following format: "0A1344010400010005" (hex representation)

I would need to convert this string into an array of bytes (0x0a, 0x13, 0x44, and so forth) so that these data can be used in the following function:

$data = $this->data;

    for ($i = 0; $i < sizeof($data); $i++) {

        // 1.value right shift 8 digits (equal to divide 256)
        // 2.XOR value and incoming data, then AND 0xFF
        // 3. get an index£¨then search related index data in CRC16_TABLE
        // XOR again
        $this->value = ($this->value >> 8) ^ $this->arr[($this->value ^ $data[$i]) & 0xff];         

    }

$this->value value is 0xFFFF. $this->arr is an array containing elements: array(0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf).

I have done the following. Basically, this traverses the string and separates every 2 characters as hex rep per byte and convert them to binary string.

$data = array();
    $len = strlen($str);
    if($len % 2 == 1) $str = "0".$str;
    $len = strlen($str);
    for($i =0; $i < $len; $i=$i+2)
    {
        $data[] = hex2bin(substr($str,$i,2));
    }
    $this->data = $data;

It seems that it is generating result of value 0 all the time. Is there anything that I should have done?

Thank you so much for the help!

Foi útil?

Solução

pack can convert a hex string into a binary string (bytes 0x0a, 0x13, 0x44, and so forth):

$data = pack('H*', '0A1344010400010005');

After that, what you have done should work, with one minor change: $data[$i] is actually a string and to get the value of the corresponding byte you need ord:

for ($i = 0; $i < strlen($data); $i++) {
    $this->value = ($this->value >> 8) ^ $this->arr[($this->value ^ ord($data[$i])) & 0xFF];         
}

Outras dicas

hex2bin returns a binary string, you want an integer I think. Use ord to convert the characters to int

$data = array();
$len = strlen($str);
if($len % 2 == 1) $str = "0".$str;
$len = strlen($str);
for($i =0; $i < $len; $i=$i+2)
{
    $data[] = ord(hex2bin(substr($str,$i,2)));
}
$this->data = $data;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top