标签:十进制

1JavaScript 代码如何实现进制转换?

JavaScript 可以使用以下代码实现进制转换:

1、十进制转二进制

使用 toString() 方法,将十进制数转换为二进制字符串,如下:

const decimalToBinary = (decimalNumber) => decimalNumber.toString(2);

console.log(decimalToBinary(11)); // 1011

2、十进制转八进制

const decimalToOctal = (decimalNumber) => decimalNumber.toString(8);

console.log(decimalToOctal(11)); // 13

3、十进制转十六进制

const decimalToHex = (decimalNumber) => decimalNumber.toString(16);

console.log(decimalToHex(11)); // b

4、二进制转十进制

const binaryToDecimal = (binaryString) => parseInt(binaryString, 2);

console.log(binaryToDecimal(1011)); // 11

5、八进制转十进制

const octalToDecimal = (binaryString) => parseInt(binaryString, 8);

console.log(octalToDecimal(13)); // 11

6、十六进制转十进制

const hexToDecimal = (binaryString) => parseInt(binaryString, 16);

console.log(hexToDecimal("b")); // 11

7、二进制转十六进制

const binaryToHex = (binaryString) => {
    const decimalNumber = parseInt(binaryString, 2);
    return decimalNumber.toString(16);
};

console.log(binaryToHex(1011)); // b

8、八进制转二进制

const octalToBinary = (octalString) => {
    const decimalNumber = parseInt(octalString, 8);
    return decimalNumber.toString(2);
};

console.log(octalToBinary(13)); // 1011

9、十六进制转二进制

const hexToBinary = (hexString) => {
    const decimalNumber = parseInt(hexString, 16);
    return decimalNumber.toString(2);
};

console.log(hexToBinary("b")); // 1011

10、八进制转十六进制

const octalToHex = (octalString) => {
    const decimalNumber = parseInt(octalString, 8);
    return decimalNumber.toString(16);
};

console.log(octalToHex(13)); // b

下面将上述代码封装成一个类,完整代码如下:

class NumberConverter {
    static decimalToBinary(decimalNumber) {
        return decimalNumber.toString(2);
    }

    static decimalToOctal(decimalNumber) {
        return decimalNumber.toString(8);
    }

    static decimalToHex(decimalNumber) {
        return decimalNumber.toString(16);
    }

    static binaryToDecimal(binaryString) {
        return parseInt(binaryString, 2);
    }

    static octalToDecimal(octalString) {
        return parseInt(octalString, 8);
    }

    static hexToDecimal(hexString) {
        return parseInt(hexString, 16);
    }

    static binaryToHex(binaryString) {
        const decimalNumber = parseInt(binaryString, 2);
        return decimalNumber.toString(16);
    }

    static octalToBinary(octalString) {
        const decimalNumber = parseInt(octalString, 8);
        return decimalNumber.toString(2);
    }

    static hexToBinary(hexString) {
        const decimalNumber = parseInt(hexString, 16);
        return decimalNumber.toString(2);
    }

    static octalToHex(octalString) {
        const decimalNumber = parseInt(octalString, 8);
        return decimalNumber.toString(16);
    }
}

console.log(NumberConverter.decimalToBinary(11)); // 1011
console.log(NumberConverter.decimalToOctal(11)); // 13