Page 1 of 1

Reading Every Two Characters In A String

Posted: Sat Sep 12, 2009 4:57 pm
by zunebuggy
I have a string that is like this: 'FF336AD0075CCC'. $msg_len = strlen of this string.

I need to loop through and get every 2 characters in the string and convert it to decimal. Here is what I have but it returns a syntax error.

Code: Select all

 
    for ($msgCnt=1; $msgCnt<=$msg_len; $msgCnt +=2) {
        $hxChar=substr($keyWordString, $keyCnt-1,2);
        $hxVal=hexdec($hxChar);
        $msg_writ=$msg_writ.chr($hxVal);
 

Re: Reading Every Two Characters In A String

Posted: Sat Sep 12, 2009 4:58 pm
by requinix
For syntax, you might be missing the closing }.

What's $keyCnt?

Also, for fun

Code: Select all

$msg_writ .= implode("", array_map("chr", array_map("hexdec", str_split($keyWordString, 2))))

Re: Reading Every Two Characters In A String

Posted: Sat Sep 12, 2009 5:09 pm
by zunebuggy
keyCnt should have been msgCnt. That might be part of it. I copied that from another script I wrote that did work and missed changing the variable names in a whole line. It looks like your array line will do everything I need in one line correct?
Thanks.

Re: Reading Every Two Characters In A String

Posted: Sat Sep 12, 2009 5:25 pm
by requinix
zunebuggy wrote:It looks like your array line will do everything I need in one line correct?
If you can understand how it works you're free to use it. If not then you shouldn't: better to have something longer that you know than something shorter that you don't.