DevToolBox

Hex to Bytes - 16進数をバイト列に変換する実装例

バイナリプロトコルの解析、ファイルシグネチャの判定、暗号鍵の受け渡し――こうした場面では 「HEXの文字列」ではなく「バイト列(bytes)」そのものが必要になります。hex to bytes(hexadecimal to bytes)変換は単純に見えて、 言語ごとのAPIの違いやエンディアンの落とし穴でハマりやすいポイントです。 この記事ではPython・JavaScript・Java・Go・C#の実装例と、実務での典型的な使いどころをまとめます。

Converting hex to bytes (hexadecimal to bytes) turns a human-readable hex string into the raw byte array that binary protocols, file parsers, and crypto APIs actually expect. This guide covers the standard library call in five languages, the endianness gotcha for multi-byte numbers, and how file signatures use this exact conversion.

TL;DR

Hex Converter

HEX⇔バイナリの相互変換にも対応。スペース区切りのHEXを入力するだけで、各バイトが8bit二進数としてどう並ぶか即座に確認できます。ブラウザ完結で外部送信なし。

今すぐ試す →

1. Hex文字列とバイト列の関係 / Hex strings vs. byte arrays

HEX文字列はあくまで「文字列型」であり、プログラムはそのままではバイナリデータとして扱えません。 2桁ずつ区切って数値化した配列(バイト列/bytes/Uint8Arrayなど言語ごとに呼び名は異なる)に 変換して初めて、ファイル書き込みやネットワーク送信、ハッシュ計算などのバイナリAPIに渡せます。

hex文字列: "48656c6c6f"          (10文字の文字列)
     ↓ 2桁ずつ区切る
バイト列:  [0x48, 0x65, 0x6c, 0x6c, 0x6f]  (5要素の数値配列)
     ↓ ASCIIとして解釈
テキスト:  "Hello"

A hex string is just text. Splitting it into two-character groups and parsing each as a number produces the actual byte array that binary APIs require — this is the conversion step most beginners skip and then wonder why their crypto or file-write call rejects a plain hex string.

2. 言語別実装 / Code examples

Python

# hex -> bytes
b = bytes.fromhex("48656c6c6f")
print(b)          # b'Hello'
print(list(b))    # [72, 101, 108, 108, 111]

# bytes -> hex
b.hex()            # '48656c6c6f'
b.hex(" ")          # '48 65 6c 6c 6f' (区切り文字つき、3.8+)

JavaScript (ブラウザ / Uint8Array)

// hex -> bytes
function hexToBytes(hex) {
  const clean = hex.replace(/\s+/g, "");
  const bytes = new Uint8Array(clean.length / 2);
  for (let i = 0; i < bytes.length; i++) {
    bytes[i] = parseInt(clean.substr(i * 2, 2), 16);
  }
  return bytes;
}
hexToBytes("48656c6c6f"); // Uint8Array(5) [72, 101, 108, 108, 111]

// bytes -> hex
function bytesToHex(bytes) {
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}

Node.js (Buffer)

// hex -> bytes
const buf = Buffer.from("48656c6c6f", "hex");
console.log(buf); // <Buffer 48 65 6c 6c 6f>

// bytes -> hex
buf.toString("hex"); // '48656c6c6f'

Java

// hex -> bytes (Java 17+ の HexFormat)
byte[] bytes = HexFormat.of().parseHex("48656c6c6f");

// bytes -> hex
String hex = HexFormat.of().formatHex(bytes); // "48656c6c6f"

// Java 16以前は自前実装 or javax.xml.bind.DatatypeConverter(非推奨)

Go

import "encoding/hex"

// hex -> bytes
b, err := hex.DecodeString("48656c6c6f") // []byte{0x48, 0x65, 0x6c, 0x6c, 0x6f}

// bytes -> hex
s := hex.EncodeToString(b) // "48656c6c6f"

C#

// hex -> bytes (.NET 5+)
byte[] bytes = Convert.FromHexString("48656c6c6f");

// bytes -> hex
string hex = Convert.ToHexString(bytes); // "48656C6C6F"

3. エンディアンとマルチバイト数値 / Endianness and multi-byte numbers

1バイトの範囲(0〜255)ならエンディアンは関係ありませんが、2バイト以上の数値を バイト列として扱う場合はバイト順(エンディアン)を意識する必要があります。

方式 / Order0x12345678 のバイト列主な用途
ビッグエンディアン (Big-endian)12 34 56 78多くのネットワークプロトコル(TCP/IPのネットワークバイトオーダー)
リトルエンディアン (Little-endian)78 56 34 12x86/x64 CPUのメモリ表現、多くのファイルフォーマット

バイト列を数値として解釈する処理(struct.unpackDataView など)は 必ずエンディアンを指定する引数を持っています。プロトコルやファイル仕様に明記されたバイト順を 確認せずに変換すると、数値が正反対の桁に見えることがあります。

# Python: struct でエンディアンを指定して数値化
import struct
struct.unpack(">I", bytes.fromhex("12345678"))[0]  # 305419896 (big-endian)
struct.unpack("<I", bytes.fromhex("12345678"))[0]  # 2018915346 (little-endian)

Single bytes are endianness-free, but multi-byte integers are not: the same four bytes read big-endian versus little-endian produce completely different numbers. Always check the protocol or file format spec before interpreting a byte sequence as a number.

4. 実務でのユースケース / Where this shows up in practice

ファイルのマジックナンバー(シグネチャ)判定

拡張子は簡単に書き換えられるため、信頼できるファイル種別判定には先頭バイトのマジックナンバーを使います。ファイルの先頭数バイトをHEXに変換し、既知の シグネチャと比較するだけです。

形式 / Format先頭バイト(HEX)
PNG89 50 4E 47
JPEGFF D8 FF
GIF47 49 46 38
PDF25 50 44 46
ZIP / docx / xlsx50 4B 03 04
WebP52 49 46 46(先頭4バイト、RIFFコンテナ)

その他のユースケース

まとめ / Summary

hex to bytes変換は「2桁のHEXを1バイトの数値に変換して配列に詰める」だけの単純な処理ですが、 言語標準APIの呼び方の違いと、複数バイト数値を扱うときのエンディアンの2点だけは必ず意識してください。 ファイルシグネチャ判定のように、この変換を1回覚えておくと応用範囲が広い実務スキルです。

Converting hex to bytes is mechanically simple — split into two-character groups and parse each as a number — but two things trip people up: the standard-library call differs by language (Python's bytes.fromhex(), Node's Buffer.from(hex, 'hex'), Go's hex.DecodeString), and multi-byte integers need an explicit endianness when reinterpreted as numbers. Once mastered, the same conversion powers file-signature detection, binary protocol handling, and crypto key exchange.

Hex Converter

HEX→Binaryモードで各バイトの8bit表現を一覧表示。ファイルヘッダの16進ダンプを貼り付けて構造を確認する用途にも使えます。

今すぐ試す →

関連ツール / Related tools

関連ガイド / Related guides