How to convert a JavaScript string to byte array using ASCII encoding?
In C#, it is done as:
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(string);
I want to do the same in JavaScript for my nodejs server
How to convert a JavaScript string to byte array using ASCII encoding?
In C#, it is done as:
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(string);
I want to do the same in JavaScript for my nodejs server
Share Improve this question edited Jul 29, 2016 at 8:18 Krishna Mohan 1,5233 gold badges22 silver badges29 bronze badges asked Jul 29, 2016 at 6:22 Deepak BankaDeepak Banka 5991 gold badge7 silver badges24 bronze badges 2- You need to post the code you have already tried and explain where you are getting stuck. Please read [How to Ask a Good Question] and include an minimal reproducible example in your question – Tibrogargan Commented Jul 29, 2016 at 6:30
- nodejs.org/api/… – Bergi Commented Jul 29, 2016 at 8:58
2 Answers
Reset to default 7For Node.js this is fairly easy:
var keyByte = new Buffer(string, "ascii");
Buffer is a container of bytes, and can be treated as an array:
var bytes = new Buffer("Hello, world", "ascii");
console.log(bytes[3]); //writes 108
Most of the network and filesystem APIs take and return buffers
Update for NodeJS
const str = 'Hello world';
const buf = Buffer.from(str, 'ascii');
console.log(buf.toString('hex'));
console.log(buf.toString('base64'));