Buca Bay - Always nice

Dua tiko noqu toa loaloa, na yacana ko… laga mai…

Base conversion in PHP, Radix 255

September29

Allows you to convert to any base between 2 and 255, effectively using all the ASCII characters.

In order to convert very large numbers with arbitrary precision you’ll need the BCMath lib. Without BCMath the large numbers will not be converted correctly due to PHP not being able to do the arithmetic.

If you need to convert between bases 2-36, you can use the base_convert() function. However, converting to higher bases such as 255 has some benefits, such as “compressing” the characters.

You can successfully compress SHA1 from a 40 byte hex to a 20 byte string.

echo base255(base_convert(sha1('test'), 16, 10)));

Since there is no loss of data, it can be used as a lossless compression. Normal compression such as zlib won’t work on a SHA1 since there are no repeating patterns.

posted under php | 2 Comments »

Base conversion in JavaScript

September4

I just realized recently that you can convert between number bases in JavaScript using the built in method Object.prototype.toString() and parseInt().

Math.base = function(n, to, from) {
     return parseInt(n, from || 10).toString(to);
}

For example, to convert from decimal to hex, or hex to decimal:

// convert the decimal 10 to hex
Math.base(10, 16); // 'a'

// convert the hex 'a' to decimal
Math.base('a', 10, 16); // 10
// or
Math.base(0xA, 10); // 10

Or from hex or dec to binary:

// convert the decimal 10 to binary
Math.base(10, 2); // '1010'

// convert the hex 'a' to decimal
Math.base('a', 2, 16); // 1010

This should work for bases between 2 and 36. ie: the number of characters from 0-9a-z.

Edit: changed base() to Math.base() for better namespace

I’ve also added base conversion in PHP up to a radix of 255.

Tag Cloud