3

Hex string looks like:

$hexString = "0307wordone0Banotherword0Dsomeotherword";

$wordsCount= hexdec(substr($hexString , 0, 2));

First byte (03) is total number of words in string. Next byte is count for characters of the first word (07). And after 7 bytes there is another integer 0B which tells that next word length is 11 (0B) characters, and so on...

What should function for exploding such string to array look like? We know how many iterations there should be from $wordsCount. I've tried different approaches but nothing seems to work.

2
  • It might be more efficient to use actual integers. With this you have a word limit of 255 while you could support a word/char count of a 16bit integer. Commented Sep 11, 2014 at 10:32
  • @Flosculus - I have certainty that each word is shorter than 8bit. Commented Sep 11, 2014 at 10:36

2 Answers 2

3

This can be parsed with a simple for loop in O(n). No need for some fancy (and slow) regex solutions.

$hexString = "0307wordone0Banotherword0Dsomeotherword";
$wordsCount = hexdec(substr($hexString, 0, 2));
$arr = [];
for ($i = 0, $pos = 2; $i < $wordsCount; $i++) {
    $length = hexdec(substr($hexString, $pos, 2));
    $arr[] = substr($hexString, $pos + 2, $length);
    $pos += 2 + $length;
}
var_dump($arr);
Sign up to request clarification or add additional context in comments.

1 Comment

That is working. I've only had to change $lenght*2 since I didn't mentioned words are ASCII values in hex. Thank You Sir!
0

you can solve this by iterating a pointer on the string with a for loop.

$hexString = "0307wordone0Banotherword0Dsomeotherword";

$wordsCount= hexdec(substr($hexString , 0, 2));
$pointer = 2;
for($i = 0; $i<$wordsCount;$i++)
{
    $charCount =hexdec(substr($hexString , $pointer, 2 ));
    $word = substr($hexString , $pointer + 2, $charCount);
    $pointer = $pointer + $charCount + 2;   
    $words[] = $word;
}

print_r($words);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.