function stringToHex(str){ var val = ""; for (var i = 0; i < str.length; i++) { var v = str.charCodeAt(i).toString(16); if ( v.length < 2 ) { v = "0" + v; } val += v; } return val } function hexToStr(hex,encoding) { var trimedStr = hex.trim(); var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr; var len = rawStr.length; if (len % 2 !== 0) { alert("Illegal Format ASCII Code!"); return ""; } var curCharCode; var resultStr = []; for (var i = 0; i < len; i = i + 2) { curCharCode = parseInt(rawStr.substr(i, 2), 16); resultStr.push(curCharCode); } // encoding为空时默认为utf-8 var bytesView = new Uint8Array(resultStr); var str = new TextDecoder(encoding).decode(bytesView); return str; } /** * 输入 json 格式的授信信息 * 返回 hex 格式的登录信息 */ function auth( info ){ var str = ""; var manufactor = info.manufactor + " "; manufactor.substr(0, 8); var system = info.system + " "; system.substr(0, 8); var customer = info.customer; str = manufactor + system + customer return stringToHex( str ) } // 测试 var test = { "manufactor": "sunyard", "system": "hsm", "customer": "ICBC" } console.log( auth(test) ) console.log("hexToStr=" + hexToStr("73756e796172642068736d202020202049434243", "UTF-8")) // 73756e79617264202020202020202068736d202020202020202049434243 // 73756e796172642068736d202020202049434243