beansontoast
beansontoast

Reputation: 181

Convert number to and from alphanumeric code

Is it possible to convert from numeric to an alphanumeric code like this:

a
b
c
d
..
z
1
2
3
4
..
aa
ab
ac
ad
..
az
a1
a2
a3
a4
..
aaa
aab
aac
aad
..
aaz
aa1
aa2

etc.

I'm trying to convert large numbers to smaller length alphanumeric strings.

Upvotes: 1

Views: 6031

Answers (5)

Matthew Lymer
Matthew Lymer

Reputation: 977

Don't know why you want to do this specifically, but try changing the base from 10 to something like 32;

 base_convert($number, 10, 32);

Then to convert back

 base_convert($number, 32, 10);

As someone else pointed out - for very large numbers this may not work.

If you need to be able to handle very large numbers, check out this link:

How to generate random 64-bit value as decimal string in PHP

Upvotes: 6

DerVO
DerVO

Reputation: 3679

You can use base_convert() for changing the base of your number from 10 (decimal) to 36 (26 latin letters plus 10 arabic numerals).

The result will differ from your given example list. You have used the digits abc..xyz012..789, base_convert will use a diffent order 012..789abc..xyz.

// convert decimal to base36
echo base_convert($number_dec, 10 , 36);

// convert base36 to decimal
echo base_convert($number_b36, 36 , 10);

Translation

dec     base36
0       0
1       1
...
9       9
10      a
11      b
...
34      y
35      z
36      10
37      11
..
45      19
46      1a
...
1295    zz
1296    100
1297    101

Upvotes: 2

rodrigovr
rodrigovr

Reputation: 454

Both dechex() and base_convert() will fail with large numbers. They are limited by the maximum size and precision of int and float types internally used during conversion.

The http://php.net/manual/pt_BR/function.base-convert.php discussion has some nice helper functions (see 2, 3) that can avoid this problem by using BC-functions to do the math. The BC extension can deal with arbitrarily large numbers.

Upvotes: 0

Faisal
Faisal

Reputation: 162

base64_encode();

and for decode use

base64_decode();

Upvotes: 0

Bloafer
Bloafer

Reputation: 1326

You could use dechex to convert the number to hex

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

For example:

1000000 => f4240
1000001 => f4241
1000002 => f4242
1000003 => f4243
1000004 => f4244
1000005 => f4245
1000006 => f4246
1000007 => f4247
1000008 => f4248
1000009 => f4249
1000010 => f424a
1000011 => f424b
1000012 => f424c
1000013 => f424d
1000014 => f424e
1000015 => f424f
1000016 => f4250
1000017 => f4251
1000018 => f4252
1000019 => f4253
1000020 => f4254

To convert back, just use hexdec

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

Upvotes: 0

Related Questions