js小工具.字符串&16进制数值字符串&互转

1、

2、测试代码:

<!DOCTYPE html><html><head> <meta charset="UTF-8"> <script type="text/javascript" > <!-- window.onload = function() { // var strTest = "1234567"; // strTest = strTest.substr(2); // console.log("strTest : " + strTest); // var str ="GET / HTTP/1.1\r\n" // +"Host: www.google.com\r\n" // +"User-Agent: curl/7.43.0\r\n" // +"Accept: */*\r\n" // +"\r\n"; var str ="GET / HTTP/1.1\r\n" +"Host: www.baidu.com\r\n" +"User-Agent: curl/7.43.0\r\n" +"Accept: */*\r\n" +"\r\n"; var strHex = strToHexCharCode(str); console.log(str); console.log("字符串 转为 16进制数值的字符串:\n"); console.log(strHex); console.log(""); // strHex = "474554202f20485454502f312e310d0a486f73743a" // +"207777772e676f6f676c652e636f6d0d0a55736572" // +"2d4167656e743a206375726c2f372e34332e300d0a" // +"4163636570743a202a2f2a0d0a0d0a"; strHex = "474554202f20485454502f312e310d0a486f73743a207777772e62616964752e636f6d0d0a557365722d4167656e743a206375726c2f372e34332e300d0a4163636570743a202a2f2a0d0a0d0a"; console.log(strHex); console.log("16进制数值的字符串 转为 字符串:\n"); str = hexCharCodeToStr(strHex); console.log(str); }; //字符串转16进制 function strToHexCharCode(_str) { if(_str === "") return ""; var hexCharCode = []; hexCharCode.push("0x\n"); for(var i = 0; i < _str.length; i++) { var str = _str.charCodeAt(i).toString(16); str = LeftPad_2(str); hexCharCode.push(str); } return hexCharCode.join(""); } // 16进制转字符串 function hexCharCodeToStr(_hexCharCodeStr) { var trimedStr = _hexCharCodeStr.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); // ASCII Code Value resultStr.push(String.fromCharCode(curCharCode)); } return resultStr.join(""); } function LeftPad_2(_str) { if (_str.length == 1) return "0"+_str; return _str; } --> </script></head><body></body></html>

 

3、

4、

5、

 

相关文章