萬盛學電腦網

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

JavaScript 進制轉換完全指南:toString、parseInt、位運算實戰

JavaScript 內建支援 2~36 進制互轉,核心 API 為 `Number.prototype.toString(radix)` 與 `parseInt(string, radix)`。本文系統整理進制轉換語法、常見進制對照、位運算技巧、大數處理與實戰應用場景。

核心 API 對照表

操作方法參數範例結果
數字 → 字串 (任意進制)num.toString(radix)radix: 2~36(10).toString(2)"1010"
字串 → 數字 (任意進制)parseInt(str, radix)radix: 2~36parseInt("1010", 2)10
數字 → 16進制字串num.toString(16)-(255).toString(16)"ff"
16進制字串 → 數字parseInt(str, 16)-parseInt("ff", 16)255
數字 → 8進制字串num.toString(8)-(10).toString(8)"12"
8進制字串 → 數字parseInt(str, 8)-parseInt("12", 8)10

基本範例

<script>
var x = 6;
// 整數轉二進制字串
var binary = x.toString(2); 
console.log("binary:", binary); // "110"

// 二進制字串轉整數 (指定基數 2)
var z = "110";
var decimal = parseInt(z, 2);
console.log("decimal:", decimal); // 6

// 更多進制
console.log((255).toString(16)); // "ff"
console.log(parseInt("ff", 16)); // 255
console.log((123).toString(36)); // "3f" (0-9, a-z)
console.log(parseInt("zz", 36)); // 1295 (最大 36 進制)
</script>

常見進制應用場景

1. 二進制:位元旗標、權限掩碼

// 權限位元定義
const PERM = {
    READ:   0b0001, // 1
    WRITE:  0b0010, // 2
    EXEC:   0b0100, // 4
    ADMIN:  0b1000  // 8
};

var userPerm = PERM.READ | PERM.WRITE; // 0b0011 = 3
console.log(userPerm.toString(2)); // "11"

// 檢查權限
function hasPermission(userPerm, perm) {
    return (userPerm & perm) === perm;
}
console.log(hasPermission(userPerm, PERM.READ));  // true
console.log(hasPermission(userPerm, PERM.ADMIN)); // false

2. 十六進制:顏色、哈希、記憶體位址

// CSS 顏色
const color = 0xff6600;
console.log('#' + color.toString(16).padStart(6, '0')); // "#ff6600"

// 從顏色字串解析
function parseColor(hex) {
    return parseInt(hex.replace('#', ''), 16);
}
console.log(parseColor('#ff6600').toString(16)); // "ff6600"

// 位運算提取 RGB
const rgb = 0xff6600;
const r = (rgb >> 16) & 0xff; // 255
const g = (rgb >> 8) & 0xff;  // 102
const b = rgb & 0xff;         // 0
console.log(r, g, b);

3. Base64 編碼 (非標準進制,但常用)

// 瀏覽器原生 API
const str = "Hello World";
const encoded = btoa(str); // "SGVsbG8gV29ybGQ="
const decoded = atob(encoded); // "Hello World"

// Node.js / 通用
// Buffer.from(str).toString('base64')

進階技巧

自動補零至固定寬度

function toRadixFixed(num, radix, width) {
    return num.toString(radix).padStart(width, '0');
}

console.log(toRadixFixed(5, 2, 8));   // "00000101"
console.log(toRadixFixed(255, 16, 4)); // "00ff"
console.log(toRadixFixed(10, 8, 4));   // "0012"

大數進制轉換 (超過 Number.MAX_SAFE_INTEGER)

// 原生 Number 精度限制:2^53 - 1 = 9007199254740991
// 大數請用 BigInt (ES2020)

const big = 123456789012345678901234567890n; // BigInt 常值
console.log(big.toString(16)); // "1b6f7b8a3d5c9e7a2b4c6d8e" (精確)

// 注意:BigInt 不支援 parseInt,需用 BigInt(str) 或 BigInt('0x' + hexStr)
const bigFromHex = BigInt('0x' + '1b6f7b8a3d5c9e7a2b4c6d8e');
console.log(bigFromHex === big); // true

位運算技巧:快速判斷奇偶、截取整數

// 判斷奇偶 (比 % 2 快)
const isOdd = n => (n & 1) === 1;
const isEven = n => (n & 1) === 0;

// 截取整數 (向零取整,比 Math.trunc 快)
const trunc = n => n | 0;
console.log(trunc(3.14));   // 3
console.log(trunc(-3.14));  // -3
console.log(trunc(1e15));   // 1000000000000000

// 2 的 n 次方對齊 (向上取整)
const alignUp = (n, powerOfTwo) => (n + powerOfTwo - 1) & ~(powerOfTwo - 1);
console.log(alignUp(100, 64)); // 128

避坑指南

坑點錯誤示範正確做法
parseInt 不傳基數parseInt("010") → 8 (舊版視為八進制)永遠傳第二參數:parseInt("010", 10)
toString 基數超出範圍(10).toString(37)範圍 2~36,超出拋 RangeError
負數 toString(2)(-5).toString(2) → "-101" (非補碼)需手動處理補碼或用 (n >>> 0).toString(2)
浮點數精度(0.1).toString(2) → 無限循環小數避免浮點數進制轉換,或用定點數
BigInt 與 Number 混用1n + 1 → TypeError統一用 BigInt 或轉換後再運算

總結

  • 數字 → 字串:`num.toString(radix)` (2~36)
  • 字串 → 數字:`parseInt(str, radix)` **永遠指定基數**
  • 位元運算:`&`, `|`, `^`, `~`, `<<`, `>>`, `>>>` 配合 2 進制思維
  • 大數:用 `BigInt`,支援 `.toString(radix)`
  • 格式化:`.padStart()` 補零、`.toLocaleString()` 千分位
copyright © 萬盛學電腦網 all rights reserved