JavaScript Convert String to Bytes Function

JavaScript Convert String to Bytes Function

July 12, 2017

Just wanted to post a quick JavaScript convert string to bytes function just for myself, but I figured someone else may find it useful:

function convertToBytes(str) {
  var bytes = [];
 
  for (var i = 0; i < str.length; ++i) {
    var charCode = str.charCodeAt(i);
    bytes = bytes.concat([charCode & 0xff, (charCode / 256) >>> 0]);
  }
 
  return bytes;
}

And my slightly improved, ES6 compatible version:

function convertToBytes(str) {
  var bytes = [];
 
  Array.from(str).forEach((char) => {
    var charCode = char.charCodeAt(char);
    bytes = bytes.concat([charCode & 0xff, (charCode / 256) >>> 0]);
  });
 
  return bytes;
}

That funky bytes concatenation line simply enables the function to work with Unicode characters.

All credit goes out to BrunoLM at StackOverflow.

JavaScript Convert String to Bytes Function | Valence Software