Buca Bay - Always nice

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

ASCII to Hex in JavaScript

June14

This JavaScript will add a method to the String object, that converts the ASCII string to a hex string consisting of the equivalent character codes for each character in the String.

String.prototype.toHex = function() {
    return this.replace(/[\s\S]/g, function(s) {
        return parseInt(s.charCodeAt()).toString(16);
    });
};

Note that hex is base 16 and ASCII is based 256 so the hex string is a longer.

I recently had to save a password in hex (Hexadecimal) instead of plain ASCII since the software that came with my Netgear USB Wireless Adapter didn’t like the ASCII version for some reason.

So for example if your password is “joe”, then to convert it to the Hex equivalent would be:

'joe'.toHex()

Oddly, my computer (Vista) took the Hex password, while the printer took the ASCII version and my friends Windows 7 took the Hex.

posted under javascript | 2 Comments »

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 »
Tag Cloud