Nodejs 字符串string转字节数组byte[]

Nodejs目前还没有原生支持从string到byte[]的转换,需要自己写。可以给String对象加一个原型函数,如下示例:

String.prototype.toBytes = function(encoding){
 var bytes = [];
 var buff = new Buffer(this, encoding);
 for(var i= 0; i< buff.length; i++){
   var byteint = buff[i];
   bytes.push(byteint);
 }
 return bytes;
}

var test = function(str, encoding){
  var bytes = str.toBytes(encoding);
  console.log(bytes);
  //校验正确性
  console.log(Buffer.from(bytes).toString(encoding));
  console.log('\n');
}

test("08:9E:01:BF:AC:64","utf8");
test("","utf8");
test("abc中文","utf8")

输出:

[ 48, 56, 58, 57, 69, 58, 48, 49, 58, 66, 70, 58, 65, 67, 58, 54, 52 ]
08:9E:01:BF:AC:64


[]



[ 97, 98, 99, 228, 184, 173, 230, 150, 135 ]
abc中文
发布了51 篇原创文章 · 获赞 3 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/pengpengzhou/article/details/105117790