js 进制转换
js 进制转换支持 2-36 , 即 0-9a-z .
可以用于混淆、数值缩短、特殊符号转换…
// 取值 2-36 (1234).toString(36) // 把 10 进制数转为 36 进制 parseInt('ya', 36) // 把转 36 进制 ya 为 10 进制
以下是一些应用.
字符串36进制编码解码
function enStr(strLong = '你好'){ const num2 = 36; let aryLong = ''; let result = ''; for (const item of strLong) { if (aryLong.length > 0) aryLong += '|'; aryLong += item.charCodeAt().toString(num2); } return aryLong } function deStr(aryLong = 'fog|hod') { const num2 = 36 let result = '' for (const item of aryLong.split('|')) { result += String.fromCharCode(parseInt(item, num2)); } return result } console.log('enStr()', enStr('测试')) console.log('deStr()', deStr(enStr('测试')))
ip地址端口号36进制编码解码
function enServer(ip = '192.168.6.20:8080') { // 返回 ip:prot 的 36进制+位置 例: 192.168.6.20:8080 => oit6cnyo3312 const arr = [...ip.matchAll(/\.|:/g)].map(item => item. index) const addr = arr.map((item, index, arr) => index === 0 ? item : arr[index] - arr[index-1] - 1).join('') const ip36 = (Number(ip.replace(/\.|:/g, ''))).toString(36) // 转 ip 端口为 36 进制并位置 const res = ip36+addr return res } function deServer(str = 'oit6cnyo3312') { // 转 36进制+位置为 ip:prot 例: oit6cnyo3312 => 192.168.6.20:8080 const [, ip36, addr] = str.match(/(.*)(.{4})/) const ip = String(parseInt(ip36, 36)) const re = new RegExp(addr.replace(/(\d)(\d)(\d)(\d)/, '(\\d{$1})(\\d{$2})(\\d{$3})(\\d{$4})(\\d+)')) const res = ip.replace(re, '$1.$2.$3.$4:$5') return res } console.log('enServer', enServer('127.0.0.1:8888')) console.log('deServer', deServer(enServer('127.0.0.1:8888')))