最近学习蓝牙模块,将字符串转换成16进制形式发到蓝牙模块,但转换出来开头缺少符号“0x”,如字符串"1234",转成 ["31", "32", "33", "34"],但蓝牙模块无法识别,只能识别[0x31, 0x32, 0x33, 0x34]这个形式,网上下载代码
stringToBytes:function(str){
var array = [];
array.push("0x");
for (var i = 0; i < str.length; i++) {
array.push((str.charCodeAt(i)).toString(16));
}
array.join("");
console.log(array);
let buffer = new Uint16Array (array).buffer;
return array;
},
但结果["31", "32", "33", "34"]一样是无,求大神救助。
var str = "1234";
var val = [];
for (var i = 0; i < str.length; i++) {
val.push("0x" + str.charCodeAt(i).toString(16))
}
console.log(val)
[0x31, 0x32, 0x33, 0x34] 就是 [49, 50, 51, 52]吧
function stringToBytes(str){
var array = [];
for (var i = 0; i < str.length; i++) {
array.push(parseInt((str.charCodeAt(i)).toString(16), 16));
}
array.join("");
console.log(array);
let buffer = new Uint16Array (array).buffer;
return array;
}
--↓↓👍点赞是回答的动力哦