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')))