Welcome to WebmasterWorld Guest from 54.145.85.87

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

# Function that Converts Numeric Into Alphanumic

#### BlackRaven

7:07 pm on Jun 6, 2010 (gmt 0)

#### Full Member

joined:June 16, 2004
posts:232

Hi i am looking for a function that converts a numeric value, ie 0, 1, 2 ,3 into a four digit alpha number equivalent ie aaaa, aaab, aaac. Not sure how you would go about doing it when you reach double and triple digits.

the values should be the following for the alpha numeric

0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
12 m
13 n
14 o
15 p
16 q
17 r
18 s
19 t
20 u
21 v
22 w
23 x
24 y
25 z
26 A
27 B
28 C
29 D
30 E
31 F
32 G
33 H
34 I
35 J
26 K
27 L
28 M
29 N
30 O
31 P
32 Q
33 R
34 S
35 T
36 U
37 V
38 W
39 X
40 Y
41 Z
42 0
43 1
44 2
45 3
46 4
47 5
48 6
49 7
50 8
51 9

#### astupidname

6:07 am on June 8, 2010 (gmt 0)

#### Preferred Member

joined:Aug 18, 2008
posts:408

Note: you had an error in your list, went from 35(J) to 26(K) there! Threw me for a minute there!
O.k, I took it on as a somewhat interesting experiment. One issue here is, that mainly due to the four character code limitation it also limits the size of the number which may be encoded. Using the characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 that is a total of 62 characters which essentially limits the maximum size of the encodable number to 14776335 (number of encoding chars to the fourth power, minus 1).
The way the below example works is, where \$c is the number of encoding characters given, the first character (of the encoded code) represents the number (integer) of times \$c to the third power is contained within the given number, the second character represents the number of times \$c to the second power is contained in the remainder from previous equation, the third character represents the number of times \$c is contained within the remainder of the previous equations, and the fourth character represents the remainder of the number divided by \$c - or the number it's self if less than \$c.
The finished result: a NumberEncoder class with two methods - encode and decode:

NumberEncoder.php
``<?php//>NumberEncoder.phpclass NumberEncoder {    const keyString = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';    private \$_key;    function __construct(\$ks = self::keyString) {        \$this->_key = \$ks;    }     //encodes a number to a four character code.     //maximum size of \$num accepted will be dependant upon the fact that we are only     //encoding to four characters, and upon the number of characters given to use for     //encoding. With the default NumberEncoder::keyString (62 characters) the largest     //encodable number is 14776335     //Formula for determining maximum number size is: number of encoding characters to the fourth power - 1    public function encode(\$num) {        \$ca = str_split(\$this->_key); //62 items in \$ca, if using NumberEncoder::keyString        \$c = count(\$ca); //number of chars we have to work with for encoding        \$c2 = pow(\$c, 2);        \$c3 = pow(\$c, 3);        \$c4 = pow(\$c, 4);        if (!is_int(\$num) || \$num >= \$c4) {            return null;        }        //fourth char will be the remainder of the number divided by \$c, if number is greater than \$c        //third char will be the number of multiples of \$c        //second char will be the number of multiples of \$c*\$c        //first char will be the number of multiples of \$c*\$c*\$c        //maximum number of multiples is of course limited to \$c        \$d1 = \$d2 = \$d3 = 0;        \$d4 = \$num % \$c;        if (\$num < \$c) {            \$d4 = \$num;        } else if (\$num < \$c2) {            \$d3 = floor(\$num / \$c); //number of multiples of \$c        } else if (\$num < \$c3) {            \$d2 = floor(\$num / \$c2); //number of multiples of \$c2            \$d3 = floor((\$num - (\$c2 * \$d2)) / \$c); //number of multiples of \$c        } else { //\$num is >= \$c3 && < \$c4            \$d1 = floor(\$num / \$c3); //number of multiples of \$c3            \$d2 = floor((\$num - (\$c3 * \$d1)) / \$c2); //number of multiples of \$c2            \$d3 = floor((\$num - ((\$c2 * \$d2) + (\$c3 * \$d1))) / \$c); //number of multiples of \$c        }        return \$ca[\$d1].\$ca[\$d2].\$ca[\$d3].\$ca[\$d4];    }     //decodes a number which was encoded with this class's encode method    public function decode(\$str) {        \$key = \$this->_key;        \$matchkey = preg_replace("/(\(|\))/", '\\$1', \$key);        //check \$str is of proper type and length, and does not contain characters other than our key contains        if (!((is_string(\$str) || is_int(\$str)) && strlen(\$str) == 4) || preg_match("/[^\$matchkey]/", \$str)) {            return null;        }        \$caf = array_flip(str_split(\$key));        \$sa = str_split(\$str);        \$c = count(\$caf); //62 items in \$caf, number of chars we have to work with for encoding/decoding        \$c2 = \$c * \$c; //3844 (with 62 characters given for encoding use)        \$c3 = \$c * \$c * \$c; //238328 (with 62 characters given for encoding use)        \$d1 = \$caf[\$sa[0]] * \$c3;        \$d2 = \$caf[\$sa[1]] * \$c2;        \$d3 = \$caf[\$sa[2]] * \$c;        \$d4 = \$caf[\$sa[3]];        return \$d1 + \$d2 + \$d3 + \$d4;    }}?>``

A usage example:

number_encoder_test.php
``<?php//>number_encoder_test.phpfunction erp(\$s, \$color = 0) {    \$colors = array('black', 'red', 'green', 'blue');    echo '<p style="color:'.\$colors[\$color].'; margin:4px;">'.\$s."</p>\n";}function pre(\$o) {    echo '<pre style="margin:4px; padding:0 4px;">'."\n";    print_r(\$o);    echo "</pre>\n";}include('NumberEncoder.php'); //import the NumberEncoder class\$NE = new NumberEncoder(); //not passing a string to NumberEncoder uses the default key which is NumberEncoder::keyStringerp('NumberEncoder::keyString = '.NumberEncoder::keyString);//some test numbers to run through:\$nArr = array(1, 12, 50, 61, 62, 104, 233, 675, 3400, 3844, 3845, 16788, 123000, 238328, 1333666, 9888777, 14776335, 14776336);foreach (\$nArr as \$i => \$n) {    \$encoded = \$NE->encode(\$n);    if (\$encoded !== null) {        \$decoded = \$NE->decode(\$encoded);        pre('\$n = '.\$n.', \$encoded = '.\$encoded.', \$decoded = '.\$decoded);    } else {        erp('\$n = '.\$n.', NUMBER TOO LARGE, CAN NOT ENCODE TO 4 CHARACTERS WITH THE ENCODE CHARACTERS GIVEN!');    }}erp('Example of using NumberEncoder with a different, longer key:', 1);\$key = str_split(NumberEncoder::keyString.'[]{}()*%\$#@!?,.;:"\'^&');\$c = count(\$key);\$max = pow(\$c, 4) - 1;erp('Number of chars for encoding: '.\$c.', maximum size of acceptable number (see notes in NumberEncoder->encode): '.\$max, 1);shuffle(\$key); //randomize the order of the characters\$NE2 = new NumberEncoder(implode('', \$key));foreach (\$nArr as \$i => \$n) {    \$encoded = \$NE2->encode(\$n);    if (\$encoded !== null) {        \$decoded = \$NE2->decode(\$encoded);        pre('\$n = '.\$n.', \$encoded = '.\$encoded.', \$decoded = '.\$decoded);    } else {        erp('\$n = '.\$n.', NUMBER TOO LARGE, CAN NOT ENCODE TO 4 CHARACTERS WITH THE ENCODE CHARACTERS GIVEN!');    }}?>``

Enjoy!

#### astupidname

6:27 am on June 8, 2010 (gmt 0)

#### Preferred Member

joined:Aug 18, 2008
posts:408

Oh, by the way, forgot to mention that if you copy and paste my previous codes, do not do so from Internet Explorer, as it will lose it's formatting. Best copied and pasted from other browser such as Firefox. (don't hate IE for it, it's the forums fault:).

#### astupidname

7:49 am on June 8, 2010 (gmt 0)

#### Preferred Member

joined:Aug 18, 2008
posts:408

Found an oops, guess I had not refreshed enough times, thought the decode method was working fine with the checking for appropriate characters, but now it's throwing fits if using special characters as in my second example in the usage example. Abandoning the preg_match as any regEx cures I throw at it are not working as should. Change the decode function in the NumberEncoder class to the following and it's all good even with special characters then:

``         //decodes a number which was encoded with this class's encode method    public function decode(\$str) {        \$key = \$this->_key;        //check \$str is of proper type and length        if (!((is_string(\$str) || is_int(\$str)) && strlen(\$str) == 4)) {            return null;        }        \$caf = array_flip(str_split(\$key));        \$sa = str_split(\$str);        foreach (\$sa as \$s) { //verify the \$str did not contain characters which are not in our \$key            if (!array_key_exists(\$s, \$caf)) {                return null;            }        }        \$c = count(\$caf); //62 items in \$caf, number of chars we have to work with for encoding/decoding        \$c2 = \$c * \$c; //3844 (with 62 characters given for encoding use)        \$c3 = \$c * \$c * \$c; //238328 (with 62 characters given for encoding use)        \$d1 = \$caf[\$sa[0]] * \$c3;        \$d2 = \$caf[\$sa[1]] * \$c2;        \$d3 = \$caf[\$sa[2]] * \$c;        \$d4 = \$caf[\$sa[3]];        return \$d1 + \$d2 + \$d3 + \$d4;    }``