Skip to content

实现36进制转换

🕒 Published at:

代码如下:

js
import { isString, isNumber } from 'lodash-es'

/**
 * @author oliver lou
 * @Date 2021-03-23 16:30:44
 * @description 三十六进制的字符串转为十进制数字,支持整数(包括0、正整数和负整数),没有考虑a和A大小写的问题,只支持小写
 * @param {string} str
 * @return {number}
 */
export function to10(str) {
    if (!isString(str)) {
        throw new TypeError('str must be a string!');
    };
    let map = new Map();
    for (let i = 0; i < 36; i++) {
        if (i >= 0 && i <= 9) {
            map.set(i, i);
        } else {
            map.set(String.fromCharCode(i + 87), i);
        }
    }
    if (str.startsWith('-')) {
        console.log(str.slice(1));
        const arr = str.slice(1).split('').reverse();
        let result = 0;
        arr.forEach((item, i) => {
            result += map.get(item) * Math.pow(36, i);
        })
        return -result;
    } else {
        const arr = str.split('').reverse();
        let result = 0;
        arr.forEach((item, i) => {
            result += map.get(item) * Math.pow(36, i);
        })
        return result;
    }
}

/**
 * @author oliver lou
 * @Date 2021-03-23 18:10:30
 * @description 十进制数字转三十六进制字符串,支持整数(包括0、正整数和负整数),没有考虑a和A大小写的问题,只支持小写
 * @param {number} n
 * @return {string}
 */
export function to36(n) {
    if (!isNumber(n)) {
        throw new TypeError('n must be a number');
    }

    let map = new Map();
    for (let i = 0; i < 36; i++) {
        if (i >= 0 && i <= 9) {
            map.set(i, i);
        } else {
            map.set(i, String.fromCharCode(i + 87));
        }
    }

    let arr = [];
    function _core(n) {
        while (n) {
            let res = n % 36;
            arr.unshift(map.get(res));
            n = Math.floor(n / 36);
        }
        return arr.join('');
    }

    if (n < 0) {
        return '-' + _core(-n);
    } else {
        return _core(n);
    }
}