2

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?

Dulguuntur
  • 43
  • 3
  • 9

3 Answers3

4

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 :)

mgreif
  • 131
  • 6
2

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 
RomMer
  • 909
  • 1
  • 8
  • 19
0

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 
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
  • you only get the ascii code for the first character of the string doing it. The question is not totally clear but i don't think it's what he wants – RomMer May 12 '17 at 08:10