Base62 编码与解码工具

解码 Base62

关于 Base62

什么是 Base62?

本 Base62 变体把字节视为一个大端整数,并用固定字母表 0-9A-Za-z 表示。开头的零字节会变成开头的字符 0,因此解码可完整恢复原字节序列。

为什么使用 Base62?

Base62 适合 URL 或数据库中的紧凑无标点标识符。Base62 没有统一标准,双方必须采用相同的字母表顺序和前导零规则;这种可逆编码不是哈希或加密,也不含校验和。

JavaScript 中的 Base62

// npm install base-x
import basex from 'base-x';

const base62 = basex('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');

const encoded = base62.encode(Buffer.from('Hello'));
console.log(encoded);
// Output: 5TP3P3v

const decoded = Buffer.from(base62.decode('5TP3P3v')).toString('utf8');
console.log(decoded);
// Output: Hello
				

Go 中的 Base62

package main

import (
	"fmt"

	"github.com/eknkc/basex"
)

func main() {
	base62, _ := basex.NewEncoding("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")

	encoded := base62.Encode([]byte("Hello"))
	fmt.Println(encoded)
	// Output: 5TP3P3v

	decoded, _ := base62.Decode(encoded)
	fmt.Println(string(decoded))
	// Output: Hello
}
				

PHP 中的 Base62

<?php
// composer require tuupola/base62
require 'vendor/autoload.php';

$base62 = new Tuupola\Base62;

$encoded = $base62->encode("Hello");
echo $encoded . "\n";

$decoded = $base62->decode($encoded);
echo $decoded . "\n";
// Output: Hello