Gareth Heyes posted a fun little challenge and I couldn’t help but attack it. It took me longer than I thought. Not to be a spoiler, but at some point you have to convert octals to ASCII values. Now, I have done decimal to ASCII, binary to ASCII, and even hex to ASCII, but never octal to ASCII. Searching around, I found everyone seemed to use PHP, ASP, or some sort of “higher” level programming.
I found some really old code on some google cache, which I lost the url to, and it seemed to work. By working, I mean, the idea was right, the code wasn’t. After fooling around with it for a bit, I got something like the following.
String.prototype.octToAscii = function() { var temp = '', result = '', input = this + '%'; for(i = 0; i < input.length; i++) { if (input.charAt(i) != '%') { temp += input.charAt(i); } else if (temp != '') { var running = 0; var notMatchedYet = true; for(j = 0, k = temp.length - 1; k >= 0; j++, k--) { if( (temp.match("\\n")) && (notMatchedYet) ) { k--; notMatchedYet = false; } partial = temp.charAt(j) * Math.pow(8, k); running += partial; } result += String.fromCharCode(running); temp = ''; } } return result.replace(/%40%/g, "%40<br />%") };
Nice work! I’m glad you looked for a javascript solution that was my intention to have a simple challenge which demonstrated some of the techniques on my blog.
[...] while back, The Spanner’s very own Gareth Heyes posted a decent challenge. As I stated in a previous posting I took on the challenge. It didn’t take as long as I thought it would, but it was still [...]
How do i use it?