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 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