Hi Guys,
So sometimes we need ASCII conversions to see what an int value equates to in terms of ASCII char.
Alright here is a quick tip that you can use
int –> char
We will use Javscript’s inbuilt function that is part of String class called fromCharCode to see an translate an int to char
[geshi lang=”javascript” nums=”1″ target=”_self” ]
1 2 |
var i=97; console.log(String.fromCharCode(i)); |
1 |
// above line will print a |
1 2 |
var i=65; console.log(String.fromCharCode(i)); |
1 |
// above line will print A |
A reference to this function can be found here
http://www.w3schools.com/jsref/jsref_fromcharcode.asp
Lets do a complete opposite now
char –> int
We will use Javscript’s inbuilt function that is part of String class called charCodeAt to see an translate an int to char
[geshi lang=”javascript” nums=”1″ target=”_self” ]
1 2 3 |
var chr ='a'; console.log(chr.charCodeAt(0)); // should print 97 |
1 2 3 |
var chr ='A'; console.log(chr.charCodeAt(0)); // should print 65 |
So as you see that its pretty dead simple to do this stuff.
One tip I have for you is that if you are just using
1 |
charCodeAt |
function on a string length of 1 then you dont need to pass index value. But I found it good practise to use the function the way it is suppose to be used.
So if you don’t want to use index then above can be rewritten as
[geshi lang=”javascript” nums=”1″ target=”_self” ]
1 2 3 |
var ch ='a'; console.log(ch.charCodeAt()); // should still print 97 |
1 2 3 |
var ch ='A'; console.log(ch.charCodeAt()); // should still print 65 |
More information on this function can be found here
http://www.w3schools.com/jsref/jsref_charcodeat.asp
I hope this helps
If I miss something in this post please use comments to add your knowledge that can be shared with many
Cheers,
Advertisement
Leave a Reply