开发小程序蓝牙开锁,应用到了16进制相关操作方法,记录一下相关方法。
// ArrayBuffer转16进制字符串 export const ab2hex = (buffer) => { const hexArr = Array.prototype.map.call( new Uint8Array(buffer), function(bit) { return ('00' + bit.toString(16)).slice(-2); } ) return hexArr.join(''); } // 16进制字符串转ArrayBuffer export const string2buffer = (str) => { const buf = new ArrayBuffer(str.length / 2); const bufView = new Uint8Array(buf); for (let i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = parseInt(str.slice(i * 2, i * 2 + 2), 16); } return buf; } // 16进制字符串分隔每两个字符成数组 export const hexStr2ToArray = (str) => { const arr = []; for (let i = 0, len = str.length / 2; i < len; i++) { arr.push(str.slice(i * 2, i * 2 + 2)); } return arr; } // 10进制数组转16进制字符串 export const intArrToHexStr = (arr) => { let rArr = []; for (let i = 0, len = arr.length; i < len; i++) { const item = arr[i].toString(16); rArr.push(item.length === 1 ? '0' + item : item); } return rArr.join(''); }