JavaScript/Pythonで2進数・8進数・16進数を相互変換する方法【完全ガイド】

 

プログラミングにおいて、異なる進数間での変換は基本的で重要な操作です。この記事では、2進数、8進数、16進数の数値・文字列を相互に変換する方法を、JavaScriptとPythonのサンプルコードと共に詳しく解説します。

10進数から各進数への変換

JavaScript

let num = 255;
console.log(num.toString(2));  // "11111111" (2進数)
console.log(num.toString(8));  // "377" (8進数)
console.log(num.toString(16)); // "ff" (16進数)

Python

num = 255
print(bin(num))  # "0b11111111" (2進数)
print(oct(num))  # "0o377" (8進数)
print(hex(num))  # "0xff" (16進数)

各進数から10進数への変換

JavaScript

console.log(parseInt("11111111", 2));  // 255
console.log(parseInt("377", 8));       // 255
console.log(parseInt("ff", 16));       // 255

Python

print(int("11111111", 2))  # 255
print(int("377", 8))       # 255
print(int("ff", 16))       # 255

進数間の直接変換

2進数から16進数

// JavaScript
let binary = "11111111";
let hex = parseInt(binary, 2).toString(16);
console.log(hex); // "ff"
# Python
binary = "11111111"
hex_val = hex(int(binary, 2))[2:]
print(hex_val)  # "ff"

16進数から8進数

// JavaScript
let hex = "ff";
let octal = parseInt(hex, 16).toString(8);
console.log(octal); // "377"
# Python
hex_val = "ff"
octal = oct(int(hex_val, 16))[2:]
print(octal)  # "377"

実用的な変換関数

JavaScript版

class BaseConverter {
  static toBinary(num) {
    return typeof num === 'string' ? 
      parseInt(num, 10).toString(2) : num.toString(2);
  }
  
  static toOctal(num) {
    return typeof num === 'string' ? 
      parseInt(num, 10).toString(8) : num.toString(8);
  }
  
  static toHex(num) {
    return typeof num === 'string' ? 
      parseInt(num, 10).toString(16) : num.toString(16);
  }
}

Python版

class BaseConverter:
    @staticmethod
    def to_binary(num):
        return bin(int(num))[2:] if isinstance(num, str) else bin(num)[2:]
    
    @staticmethod
    def to_octal(num):
        return oct(int(num))[2:] if isinstance(num, str) else oct(num)[2:]
    
    @staticmethod
    def to_hex(num):
        return hex(int(num))[2:] if isinstance(num, str) else hex(num)[2:]

エラーハンドリング

JavaScript

function safeBaseConvert(value, fromBase, toBase) {
  try {
    let decimal = parseInt(value, fromBase);
    if (isNaN(decimal)) throw new Error("Invalid input");
    return decimal.toString(toBase);
  } catch (error) {
    return "変換エラー: " + error.message;
  }
}

Python

def safe_base_convert(value, from_base, to_base):
    try:
        decimal = int(value, from_base)
        if to_base == 2:
            return bin(decimal)[2:]
        elif to_base == 8:
            return oct(decimal)[2:]
        elif to_base == 16:
            return hex(decimal)[2:]
        else:
            return str(decimal)
    except ValueError as e:
        return f"変換エラー: {e}"

まとめ

進数変換は、組み込み関数を使用することで簡単に実装できます。JavaScriptではparseInt()toString()、Pythonではint()bin()oct()hex()関数を活用しましょう。エラーハンドリングを含めた実装により、より堅牢なコードが書けます。

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>ゼロから始めるPython爆速講座