简体   繁体   中英

How can I convert ASCII code to a word using JavaScript for loop

Looking to solve the following code in order to come up with the name for the below array

 let name=[42,67,74,62,6A,1F,58,64,60,66,64,71];
 for(let i=0;i<name.length;i++)
 {
 name[i] =name[i]+1;
 }

Any suggestions what would be the output?

Thanks

Your initial array is not a valid array because 6A and 1F are not valid numbers in JavaScript. Furthermore, if all the numbers in the array are hexidecimal numbers, you would need to precede them with 0x for them to behave correctly (because the base10 number 42 is not the same as the base16 number 42). So lets get your array in order first:

let name = [0x42,0x67,0x74,0x62,0x6A,0x1F,0x58,0x64,0x60,0x66,0x64,0x71];

We could have also used strings and parsed them into base16 (hex) numbers:

let name = ['42','67','74','62','6A','1F','58','64','60','66','64','71'].map(n => parseInt(n, 16));

Now we can use String.fromCharCode to determine what the array says:

name.map(String.fromCharCode).join('')

Though I'm not sure what that says or means...

Because we don't know which base the numbers represent and the output for hex doesn't say anything we try bases from 2 - 30 and check if for some base the output is something valid.

Note: to remove all non printable ASCII characters we use the regexp

/[^ -~]+/g

Instead of using JavaScript here there are a lot of online decoder tools like https://geocaching.dennistreysa.de/multisolver/ .There you can type in your input and press decode and it will decode in a lot of ways. This would be a more convenient way to get a word from a input than using JavaScript.

 let name = ['42','67','74','62','6A','1F','58','64','60','66','64','71']; const ob = {}; for(let i = 2; i <= 30; i++){ let temp = name.map(x => parseInt(x, i)); // Remove the non printable ASCII Characters let tempRes = String.fromCharCode(...temp).replace(/[^ -~]+/g, ""); ob[`Base${i}`] = tempRes; } console.log(ob);

You want something this?

 let name = [42,67,74,62,0x6A,0x1F,58,64,60,66,64,71]; var str = ""; for(let i=0;i<name.length;i++) { str+=String.fromCharCode(name[i]); } console.log(str);

Or even:

 let name = [42,67,74,62,0x6A,0x1F,58,64,60,66,64,71]; console.log(String.fromCharCode(...name));

*NOTE your values are in hexadecimal base you should specify it by adding 0x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM