Reputation: 51
I am trying to convert length message to ascii. My length message is like
var ll = "0170";
In node js , is there some kind of function which converts into ascii? Please help?
Upvotes: 1
Views: 8541
Reputation: 640
It is straightforward in javascript you can use the code below but you need to handle failure cases based on your requirements else you can use the npm package which provides ascii-text-converter with all error handling.
function AsciiToText(ascii: string) {
const asciiArray = ascii
.split(" ")
.map((code) => parseInt(code.trim(), 10))
.filter((item) => !isNaN(item));
const sentence = asciiArray
.map((asciiValue) => String.fromCharCode(asciiValue))
.join("");
return sentence;
}
Upvotes: 0
Reputation: 131
Here's a simple function(ES6) which converts a string into ASCII characters using charCodeAt()
const toAscii = (string) => string.split('').map(char=>char.charCodeAt(0)).join(" ")
console.log(toAscii("Hello, World"))
Output:
-> 72 101 108 108 111 44 32 87 111 114 108 100
You could create a prototype function aswell. There are many solutions :)
Upvotes: 4
Reputation: 1089
you can't have an ascii code for a whole string.
An ascii code is an integer value for a character, not a string. Then for your string "0170"
you will get 4 ascii codes
you can display these ascii codes like this
var str = "0170";
for (var i = 0, len = str.length; i < len; i++) {
console.log(str[i].charCodeAt());
}
Ouput : 48 49 55 48
Upvotes: 2
Reputation: 20098
use charCodeAt() function to covert asscii format.
var ll = "0170";
function ascii (a) { return a.charCodeAt(); }
console.log(ascii(ll[0]),ascii(ll[1]), ascii(ll[2]), ascii(ll[3]) )
result:
48 49 55 48
Upvotes: 0