最近学习蓝牙模块,将字符串转换成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"]一样是无,求大神救助。
[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; }
--↓↓👍点赞是回答的动力哦
stringToBytes:function(str){
var array = [];
for (var i = 0; i < str.length; i++) {
array.push(parseInt((str.charCodeAt(i)).toString(16), 16));
}
console.log(array);
let buffer = new Uint8Array (array).buffer;
return array;
},
startwrite: function () {
let that=this;
let array = [0x31, 0x32, 0x33, 0x34]; //输入这个array蓝牙模块能够识别为1234
let buffer=new Uint8Array(array).buffer;
wx.writeBLECharacteristicValue({
deviceId: that.data.current_device,
serviceId: that.data.current_service,
characteristicId: that.data.current_characteristic,
value: that.stringToBytes("1234"), //输入这个无任何显示,换成array就可以
success: function (res) {
console.log("writeBLECharacteristicValue success", res.errMsg)
}
})
},
stringToBytes:function(str){
var array = [];
for (var i = 0; i < str.length; i++) {
array.push(parseInt((str.charCodeAt(i)).toString(16), 16));
}
console.log(array);
let buffer = new Uint8Array (array).buffer;
return buffer;
}
https://www.jianshu.com/p/20419462e381
文末有git
--↓↓👍点赞是回答的动力哦
var str = "1234"; var val = []; for (var i = 0; i < str.length; i++) { val.push("0x" + str.charCodeAt(i).toString(16)) } console.log(val)