PHP String->Decimal->String

I needed to turn a string into a decimal, for creation of a unique ID and be able to reverse it.

To turn string to decimal, we convert it to ASCII char codes, then concat the whole mess together. I know it’s not the cleanest, and far from the most efficient, but it gets the job done quickly.

function string2dec($string) {
    // take a string, convert it to a massive long list of decimal triples representing the ASCII values
    //
    $ret = '';
    for ($i=0; $i<strlen($string); $i++) { //
        for each char of the string, turn it into a ASCII code with ord, zero pad it
        $ret .= str_pad(ord(substr($string,$i,1)),3,'0', STR_PAD_LEFT);
    }
    return $ret;
}

And to reverse, take the triplet chunks, and turn them back into characters.

function dec2string($dec) {
    // take a dec created by string2dec and reverse the process
    //
    $ret = '';
    $padLen = ceil(strlen($dec)/3)*3;
    // because leading 0s might get dropped, pad up to next [strlen is multiple of 3], and the
    // $dec string contains whole triplets
    $pad = str_pad($dec,$padLen,'0',STR_PAD_LEFT);
    for ($i=0; $i<(strlen($pad)/3); $i++) {
        $ret .= chr(substr(strval($pad), $i*3, 3));
    }
    return $ret;
}

So sue me. You’re only looking at this because you were too lazy to type it yourself and want a quick dirty fix. I don’t write PHP anymore…

Codemonkey of Node.js, Django, PHP and all things HTML5 Solving tech challenges, one bit at a time.

Posted in PHP Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*