Uint8Arrayとbase64・Hex文字列を相互に変換する
Uint8ArrayのfromBase64・toBase64・fromHex・toHexで、バイト列とbase64や16進数(Hex)の文字列を相互に変換できます。btoaで自作していた変換を置き換える使い方とオプションを説明します。
- Chrome140
- Edge140
- Firefox133
- Safari18.2
はじめに
Uint8Array.fromBase64()とtoBase64()、fromHex()、toHex()は、バイト列のUint8Arrayとbase64や16進数(Hex)の文字列を相互に変換するメソッドです。Chrome 140が対応して、Baseline 2025に入りました。
英数字だけの文字列は、btoa()とatob()でbase64にできます。ただ、btoa()はLatin-1の範囲の文字しか受け取りません。日本語を含む文字列やハッシュ値は、バイト列をString.fromCharCode()で1バイト1文字の文字列にしてから渡すので、大きなバイト列ではそこで失敗します。base64urlや16進数への変換は、自分で書くしかありませんでした。
Uint8Arrayのメソッドなら、どれも1回の呼び出しで変換できます。
const bytes = new Uint8Array([72, 101, 108, 108, 111]);
// Uint8Array → base64
console.log(bytes.toBase64()); // "SGVsbG8="
// base64 → Uint8Array
console.log(Uint8Array.fromBase64("SGVsbG8=")); // Uint8Array([72, 101, 108, 108, 111])
// Uint8Array → Hex
console.log(bytes.toHex()); // "48656c6c6f"
// Hex → Uint8Array
console.log(Uint8Array.fromHex("48656c6c6f")); // Uint8Array([72, 101, 108, 108, 111])文字列からUint8Arrayを作るときは静的メソッドのfromBase64()とfromHex()を、Uint8Arrayを文字列にするときはインスタンスメソッドのtoBase64()とtoHex()を呼びます。
自作の変換との違い
これまでは、次のような関数を自分で書いていました。
// Uint8Array → base64
function uint8ArrayToBase64(uint8Array: Uint8Array): string {
return btoa(String.fromCharCode(...uint8Array));
}
console.log(uint8ArrayToBase64(new Uint8Array([72, 101, 108, 108, 111]))); // "SGVsbG8="
// base64 → Uint8Array
function base64ToUint8Array(base64: string): Uint8Array {
return new Uint8Array([...atob(base64)].map(c => c.charCodeAt(0)));
}
console.log(base64ToUint8Array("SGVsbG8=")); // Uint8Array([72, 101, 108, 108, 111])
// Uint8Array → Hex
function uint8ArrayToHex(uint8Array: Uint8Array): string {
return [...uint8Array].map(b => b.toString(16).padStart(2, '0')).join('');
}
console.log(uint8ArrayToHex(new Uint8Array([72, 101, 108, 108, 111]))); // "48656c6c6f"
// Hex → Uint8Array
function hexToUint8Array(hex: string): Uint8Array {
const bytes = [];
for (let i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.slice(i, i + 2), 16));
}
return new Uint8Array(bytes);
}
console.log(hexToUint8Array("48656c6c6f")); // Uint8Array([72, 101, 108, 108, 111])この関数には、次の問題があります。
uint8ArrayToBase64はバイト列を引数に展開するので、大きなバイト列ではRangeErrorになります。展開できる引数の数はブラウザによって違い、1MBのバイト列はどのブラウザでも変換できません。hexToUint8Arrayは、"abc"のような奇数の長さや"zz"のような16進数でない文字列も、エラーにせず[171, 12]や[0]を返します。
Uint8Arrayのメソッドなら、toBase64()は10MBのバイト列も変換でき、fromHex()は"abc"も"zz"もSyntaxErrorにします。
日本語の文字列とハッシュ値を変換する
btoa()に"あいう"をそのまま渡すと、InvalidCharacterErrorになります。日本語を含む文字列は、TextEncoderでUTF-8のバイト列にしてから変換し、戻すときはTextDecoderで文字列にします。ハッシュ値は、crypto.subtle.digest()が返すArrayBufferをUint8Arrayにしてから変換します。
// 日本語を含む文字列をUTF-8のbase64にする
console.log(new TextEncoder().encode("あいう").toBase64()); // "44GC44GE44GG"
// UTF-8のbase64を文字列に戻す
console.log(new TextDecoder().decode(Uint8Array.fromBase64("44GC44GE44GG"))); // "あいう"
// SHA-256のハッシュ値を16進数の文字列にする
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode("hello"));
console.log(new Uint8Array(digest).toHex()); // "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"メソッドごとの使い方
fromBase64()とtoBase64()、fromHex()、toHex()のほかに、既存のUint8Arrayに書き込むsetFromBase64()とsetFromHex()もあります。
fromBase64
fromBase64()は、base64の文字列をデコードして新しいUint8Arrayを返します。第2引数のオプションで、alphabetとlastChunkHandlingを指定できます。
const base64 = "SGVsbG8=";
const uint8Array = Uint8Array.fromBase64(base64, {
alphabet: "base64url",
lastChunkHandling: "strict"
});alphabetは、受け付けるbase64の文字の種類です。既定の"base64"は+と/を使う標準のbase64を受け付け、"base64url"にすると、代わりに-と_を使うURLセーフなbase64urlを受け付けます。
const base64url = "SGV-sbG8";
// SyntaxError
const uint8Array1 = Uint8Array.fromBase64(base64url);
// Uint8Array([72, 101, 126, 177, 177, 188])
const uint8Array2 = Uint8Array.fromBase64(base64url, {
alphabet: "base64url",
});base64は、4文字ずつ3バイトに戻します。lastChunkHandlingは、最後の4文字のまとまりが欠けているときの扱いを決めます。
既定の"loose"は、最後のまとまりが=を省いた2文字や3文字でもデコードします。
const loose1 = Uint8Array.fromBase64("SGVsbG8=", { lastChunkHandling: "loose" });
const loose2 = Uint8Array.fromBase64("SGVsbG8", { lastChunkHandling: "loose" });
console.log(loose1); // Uint8Array([72, 101, 108, 108, 111])
console.log(loose2); // Uint8Array([72, 101, 108, 108, 111])"strict"は、最後のまとまりが=で埋めた4文字になっていないときや、余ったビットが0でないときにSyntaxErrorを投げます。
const strict = Uint8Array.fromBase64("SGVsbG8=", { lastChunkHandling: "strict" });
console.log(strict); // Uint8Array([72, 101, 108, 108, 111])
// SyntaxError(=で埋めていない)
Uint8Array.fromBase64("SGVsbG8", { lastChunkHandling: "strict" });
// SyntaxError(余ったビットが0でない)
Uint8Array.fromBase64("SGVsbG1=", { lastChunkHandling: "strict" });"stop-before-partial"は、最後のまとまりが欠けていれば、その手前でデコードをやめます。"SGVsbG1"の最後のbG1は3文字しかないので、手前のSGVsだけをデコードします。
const loose = Uint8Array.fromBase64("SGVsbG1", { lastChunkHandling: "loose" });
console.log(loose); // Uint8Array([72, 101, 108, 108, 109])
const stopBeforePartial = Uint8Array.fromBase64("SGVsbG1", { lastChunkHandling: "stop-before-partial" });
console.log(stopBeforePartial); // Uint8Array([72, 101, 108])toBase64
toBase64()は、Uint8Arrayの中身をbase64の文字列にします。オプションでalphabetとomitPaddingを指定できます。alphabetはfromBase64()と同じで、既定は"base64"です。
const uint8Array = new Uint8Array([72, 101, 126, 177, 177, 188]);
const base64 = uint8Array.toBase64(); // "SGV+sbG8"
const base64Url = uint8Array.toBase64({ alphabet: "base64url" }); // "SGV-sbG8"omitPaddingをtrueにすると、末尾の=を付けません。既定はfalseです。JWTのように、base64urlで=を付けない形式にするときは、alphabet: "base64url"とomitPadding: trueを一緒に指定します。
const uint8Array = new Uint8Array([251, 255]);
console.log(uint8Array.toBase64()); // "+/8="
console.log(uint8Array.toBase64({ omitPadding: true })); // "+/8"
console.log(uint8Array.toBase64({ alphabet: "base64url", omitPadding: true })); // "-_8"fromHexとtoHex
fromHex()は16進数の文字列からUint8Arrayを作り、toHex()はUint8Arrayを16進数の文字列にします。どちらもオプションはありません。fromHex()は大文字と小文字のどちらも受け付け、toHex()は小文字で返します。
console.log(Uint8Array.fromHex("4F6B")); // Uint8Array([79, 107])
console.log(new Uint8Array([79, 107]).toHex()); // "4f6b"setFromBase64とsetFromHex
setFromBase64()とsetFromHex()は、文字列をデコードして、既存のUint8Arrayに先頭から書き込みます。どちらも、読んだ文字数のreadと、書き込んだバイト数のwrittenを持つオブジェクトを返します。setFromBase64()には、fromBase64()と同じalphabetとlastChunkHandlingを指定できます。
const bytes = new Uint8Array(5);
console.log(bytes.setFromBase64("SGVsbG8=")); // { read: 8, written: 5 }
console.log(bytes); // Uint8Array([72, 101, 108, 108, 111])
console.log(bytes.setFromHex("4869")); // { read: 4, written: 2 }
console.log(bytes); // Uint8Array([72, 105, 108, 108, 111])書き込み先が足りないときは、例外にならず、入るところまで書いて止まります。setFromBase64()は4文字のまとまりごとに書くので、new Uint8Array(4)に"SGVsbG8="を書き込むと{ read: 4, written: 3 }が返り、最後の1バイトは0のままです。
おわりに
Uint8ArrayのfromBase64()とtoBase64()、fromHex()、toHex()を使えば、btoa()で自作していた変換を1回の呼び出しで書けます。日本語の文字列はTextEncoderでバイト列にしてから渡し、base64urlや=の有無はオプションで切り替えます。