NickSoft Site Admin

Joined: 13 Nov 2006 Posts: 22
|
Posted: Wed May 09, 2007 4:56 pm Post subject: JavaScript Equivalent of PHP base_convert() function |
|
|
Sometimes it is usefull to send integers as strings. For example if you want to make your link shorter (for example if users need to copy it and send it to firend) and your link contains 2-3 integers it's better to convert it to different base. Example
http://www.site.com/profile-8062344-1178730755-235235.html
Let's say that these 3 integers are profile id, some time stamp and mailbox id. Stupid example but I can't think of something better now. So you have 3 integers and long link. Here is how this link will look like with integers converted to base 36:
http://www.site.com/profile-4ssy0-jhsagz-51ib.html
Hmm 8 symbols less - not much, but if you need to send 10 time stamps with this url you will save 40 symbols.
Also integers with less characters is better for wap or html mobile sites.
If you don't like my idea about base 36 converting you can use this function to convert binary, octal, hexadecimal and decimal values.
Code: | var b36arr=['0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z'];
function base_convert(num,frombase,tobase){
var str=num.toString();
var len=str.length;
var p=1;
var b10=0;
for(i=len;i>0;i--){
b=str.charCodeAt(i-1);
c=str.charAt(i);
if(b>=48 && b<=57){
b=b-48;
}else if(b>=97 && b<=122){
b=b-97+10;
}else if(b>=65 && b<=90){
b=b-65+10;
}
b10=b10+b*p;
p=p*frombase;
}
var newval='';
var ost=0;
while(b10>0){
ost=b10%tobase;
b10=Math.floor(b10/tobase);
newval=b36arr[ost]+''+newval;
}
return newval;
} |
|
|