Wednesday, May 7, 2008

Convert an integer to an ascii character in Javascript


See my 2nd post for the revised code using built-in Javascript methods.

I was looking for a function to convert an integer into an ascii character in Javascript and could not find one. This is because Javascript does not support explicit character types, and to Javascript character is nothing but a string of length 1. This is what I have come up with. First, you define a string constant consists of all the ascii-7 characters. For non-printable characters you simply use a "?":

//reference: http://www.asciitable.com/
var asciiTable =
// 0 thru 9
"??????????" +
// 10 thru 19
"??????????" +
// 20 thru 29
"??????????" +
// 30 thru 39
"?? !\"#$%&'" +
// 40 thru 49
"()*+,-./01" +
// 50 thru 59
"23456789:;" +
// 60 thru 69
"<=>?@ABCDE" +
// 70 thru 79
"FGHIJKLMNO" +
// 80 thru 89
"PQRSTUVWXY" +
// 90 thru 99
"Z[\\]^_`abc" +
// 100 thru 109
"defghijklm" +
// 110 thru 119
"nopqrstuvw" +
// 120 thru 127
"xyz{|}~?";

Then you could have a function like this:
function itoa(i)
{
   return asciiTable.substr(i, 1);
}

Similarly, for printable characters you can have a function like this to convert character into an integer:
function atoi(c)
{
   return asciiTable.indexOf(c);
}

Hope you find this useful, and please let me know if you know any other elegant or efficient ways to do this in Javascript.

Good scripting,

Sonny

3 comments:

Anonymous said...

Cool tip! Thank you for sharing!

HJ said...

minor issue, but atoi('?') wouldn't work. is this really the only way to do this? it seems so inelegant (no offense)

HJ said...

ah I'm retarded, I totally didn't see your link to the other blog post. thanks.