Check three bytes inside a Hex string in php

341 Views Asked by At

I receive an ascii string like this :

�=message :;:-RemoteCommunicationNo version set.%�?     ���2?䋹�

I have to decode it to hex and im using bin2hex. I get this data:

  0da46500000810123d0a3b3a0a2d0a1352656d6f7465436f6d6d756e69636174696f6e12001a0f4e6f2076657273696f6e207365742e250000803f12090900000060a12b313f

Which is correct. However i want just the 3rd-4th and 5th byte (65,00,00) of this string.

Which is the most efficient way of putting these three bytes in a variable?

1

There are 1 best solutions below

0
On

It depends on what you mean by "efficient". Do you mean efficient for your coding, or efficient for performance? I'll provide both.

Best Performance

This is assuming you know the string will always be at least 10 characters long, and you never want the the first characters (first two bytes).

String parsing is expensive, and you don't want to have to parse the entire string.

http://php.net/manual/en/function.substr.php

$interestingPart = substr($yourHexString, 4, 6);  
$firstByte = substr($interestingPart, 0, 2);  
$secondByte = substr($interestingPart, 2, 2);  
$thirdByte = substr($interestingPart, 4, 2);  

Easiest to Code

http://php.net/manual/en/function.str-split.php

$bytesArray = str_split($yourHexString, 2);  
$bytesDesired = $bytesArray[2] . $bytesArray[3] . $bytesArray[4];