萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 進制轉換完全指南:任意進制字串轉十進制與十進制轉任意進制

核心 API

方向方法語法示例
任意進制 → 十進制parseInt(string, radix)radix: 2-36parseInt('11', 2) === 3
十進制 → 任意進制Number.prototype.toString(radix)radix: 2-36(152).toString(16) === '98'

詳細示例

1. 字串轉十進制 parseInt

parseInt('11', 2);    // 3   (二進制)
parseInt('77', 8);    // 63  (八進制)
parseInt('ff', 16);   // 255 (十六進制,不區分大小寫)
parseInt('z', 36);    // 35  (最大進制 36:0-9 + a-z)

parseInt('10');       // 10  (默認 radix=10)
parseInt('0xff');     // 255 (字串以 0x 開頭自動識別為 16 進制,但建議顯式傳 16)
parseInt('  123  ');  // 123 (自動去除空白)

// 陷阱:parseInt 解析浮點數字串會截斷
parseInt('12.34');    // 12 — 非四捨五入
// 正確轉浮點:Number('12.34') 或 parseFloat('12.34')

2. 十進制轉字串 toString(radix)

(152).toString(2);   // "10011000" (二進制)
(152).toString(8);   // "230"      (八進制)
(152).toString(16);  // "98"       (十六進制,小寫)
(152).toString(32);  // "4o"       (32 進制)
(35).toString(36);   // "z"        (最大 36 進制)

// 寫法注意:數字字面量直接調用需雙點或括號
152..toString(16);   // 合法:第一個點是小數點,第二個是屬性訪問
(152).toString(16);  // 推薦:括號分組,語意清晰

3. 直接書寫進制字面量(ES5+)

0b1010;   // 10  (二進制,ES6)
0o77;     // 63  (八進制,ES6)
0xff;     // 255 (十六進制,ES5)
0XFF;     // 255 (大寫也可)

進階:補零格式化

function padZero(num, len, radix = 10) {
  var s = num.toString(radix);
  while (s.length < len) s = '0' + s;
  return s;
}

padZero(15, 4, 2);    // "1111" → "1111" (已足夠)
padZero(5, 4, 2);     // "101"  → "0101"
padZero(255, 4, 16);  // "ff"   → "00ff"

// ES2017 padStart
(5).toString(2).padStart(4, '0'); // "0101"

大整數進制轉換(ES2020 BigInt)

const big = 123456789012345678901234567890n;
big.toString(16); // "1a6f2d9c5e8b3f4a5b6c" (字串)
parseInt('1a6f2d9c5e8b3f4a5b6c', 16); // 會丟失精度(超出 Number 安全整數)
// 大整數解析需用 BigInt 專用庫或手寫算法

實用封裝:通用進制轉換器

const BaseConverter = {
  // 任意進制字串 → 十進制 Number
  toDecimal: function(str, fromRadix) {
    if (fromRadix < 2 || fromRadix > 36) throw new Error('Radix 2-36');
    return parseInt(str, fromRadix);
  },
  
  // 十進制 Number → 任意進制字串
  fromDecimal: function(num, toRadix) {
    if (toRadix < 2 || toRadix > 36) throw new Error('Radix 2-36');
    return num.toString(toRadix);
  },
  
  // 任意進制 → 任意進制(中轉十進制)
  convert: function(str, fromRadix, toRadix) {
    return this.fromDecimal(this.toDecimal(str, fromRadix), toRadix);
  }
};

// 使用
BaseConverter.convert('ff', 16, 2);   // "11111111"
BaseConverter.convert('1010', 2, 16); // "a"

避坑清單

  1. 始終顯式傳遞 radix:parseInt('08') 在舊瀏覽器視為八進制返回 0,parseInt('08', 10) 正確返回 8。
  2. parseInt 只解析整數:小數用 parseFloat 或 Number。
  3. radix 範圍 2-36:超出拋錯或返回 NaN。
  4. toString 輸出小寫:大寫用 .toUpperCase()。
  5. 負數處理:(-10).toString(2) === "-1010",符號保留。

總結

JS 進制轉換核心就是 parseInt(str, radix) 和 num.toString(radix) 兩個 API。掌握 radix 範圍、字面量寫法、補零格式化、BigInt 限制,即可應對所有進制轉換場景。封裝 BaseConverter 統一項目入口,避免重複造輪子與參數錯誤。

copyright © 萬盛學電腦網 all rights reserved