简体   繁体   中英

How to convert to ascii using node.js

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?

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 

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

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 

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