0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Base64 をゼロから実装して btoa の限界を超えるツールを作った

0
Posted at

作ったもの

Base64 Toolhttps://sen.ltd/portfolio/base64-tool/

スクリーンショット

  • テキストモード(UTF-8 対応)
  • ファイルモード(画像 → データ URL)
  • URL-safe バリアント切替
  • 行折り返し(76 字、MIME 形式)
  • 元サイズと base64 サイズの比較
  • 入力方向の自動判定
  • 画像プレビュー

vanilla JS、ゼロ依存、ビルド不要node --test で 55 ケース。

btoa の限界

btoa() は Latin-1 のみ受け付ける。btoa("こんにちは") は例外を投げる。日本語を扱うなら手実装か TextEncoder の前処理が必要。

3 バイト → 4 文字のビット操作

const c1 = b1 >> 2;
const c2 = ((b1 & 0x03) << 4) | (b2 >> 4);
const c3 = ((b2 & 0x0F) << 2) | (b3 >> 6);
const c4 = b3 & 0x3F;

24 ビットを 6 ビット × 4 に分けて A-Z, a-z, 0-9, +, / の 64 文字にマッピング。

UTF-8 の 2 段構え

const bytes = new TextEncoder().encode(text);  // UTF-8 バイト列
return encode(bytes);                           // base64 エンコード

「こ」は U+3053 = UTF-8 0xE3 0x81 0x93 = base64 "44GT"。base64 自体はバイト列しか見ないので、UTF-8 化は前段で行う。

URL-safe バリアント

標準 base64 の +/ は URL で特殊文字。-_ に置換 + パディングの = を省略すると URL-safe。JWT のエンコードはこの形式。

return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

シリーズ

100+ 公開ポートフォリオ シリーズの #80 — 目標の 80%。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?