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
- HEX2桁 = 1バイト。
"48656c6c6f"(10桁)→ 5バイトの配列になる - Python:
bytes.fromhex()/ Node.js:Buffer.from(hex, "hex")が標準 - ブラウザ標準JSには専用関数がなく、
Uint8Arrayを自前で組み立てる必要がある - 複数バイトの数値はエンディアン(バイト順)に注意。プロトコル仕様を必ず確認する
- ファイルの先頭バイトをHEXに変換して比較すれば、拡張子に頼らず形式を判定できる
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バイト以上の数値を バイト列として扱う場合はバイト順(エンディアン)を意識する必要があります。
| 方式 / Order | 0x12345678 のバイト列 | 主な用途 |
|---|---|---|
| ビッグエンディアン (Big-endian) | 12 34 56 78 | 多くのネットワークプロトコル(TCP/IPのネットワークバイトオーダー) |
| リトルエンディアン (Little-endian) | 78 56 34 12 | x86/x64 CPUのメモリ表現、多くのファイルフォーマット |
バイト列を数値として解釈する処理(struct.unpack や DataView など)は 必ずエンディアンを指定する引数を持っています。プロトコルやファイル仕様に明記されたバイト順を 確認せずに変換すると、数値が正反対の桁に見えることがあります。
# 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) |
|---|---|
| PNG | 89 50 4E 47 |
| JPEG | FF D8 FF |
| GIF | 47 49 46 38 |
25 50 44 46 | |
| ZIP / docx / xlsx | 50 4B 03 04 |
| WebP | 52 49 46 46(先頭4バイト、RIFFコンテナ) |
その他のユースケース
- 暗号鍵・ハッシュ値の受け渡し: APIやCLIはHEX文字列で鍵を渡すことが多く、内部でbytesに変換してから暗号処理に使う
- バイナリプロトコルの実装: TCP/UDPソケットに直接送信するペイロードはbytes型が必須
- デバッグ用のバイナリダンプ: ログにはHEXで出力し、再現用にhex to bytesで復元する
まとめ / 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.
関連ツール / Related tools
- Hex Converter — HEX⇔テキスト⇔バイナリの変換
- Hash Generator — バイト列からハッシュ値を計算
- Number Base Converter