6

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

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 Commented Jul 29, 2016 at 6:30
  • nodejs.org/api/… Commented Jul 29, 2016 at 8:58

2 Answers 2

7

For 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

Sign up to request clarification or add additional context in comments.

Comments

6

Update for NodeJS

const str = 'Hello world';
const buf = Buffer.from(str, 'ascii');
console.log(buf.toString('hex'));
console.log(buf.toString('base64'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.