"use client"; import { useState } from "react"; import { Binary, Copy, Trash2, ArrowUpDown } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { toast } from "sonner"; // Base58 alphabet (Bitcoin style) const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const ALPHABET_MAP = ALPHABET.split('').reduce((map, char, index) => { map[char] = index; return map; }, {} as { [key: string]: number }); export default function Base58Page() { const [input, setInput] = useState(""); const copyToClipboard = async (text: string) => { if (!text) return; try { await navigator.clipboard.writeText(text); toast.success("已复制到剪贴板"); } catch { toast.error("复制失败"); } }; // Helper: Text -> Bytes const textToBytes = (text: string) => { const encoder = new TextEncoder(); return encoder.encode(text); }; // Helper: Bytes -> Text const bytesToText = (bytes: Uint8Array) => { const decoder = new TextDecoder(); return decoder.decode(bytes); }; // Encode const encode = () => { if (!input) return; const bytes = textToBytes(input); if (bytes.length === 0) return ""; let digits = [0]; for (let i = 0; i < bytes.length; i++) { for (let j = 0; j < digits.length; j++) digits[j] <<= 8; digits[0] += bytes[i]; let carry = 0; for (let j = 0; j < digits.length; ++j) { digits[j] += carry; carry = (digits[j] / 58) | 0; digits[j] %= 58; } while (carry) { digits.push(carry % 58); carry = (carry / 58) | 0; } } // Deal with leading zeros for (let i = 0; i < bytes.length && bytes[i] === 0; i++) digits.push(0); const result = digits.reverse().map(d => ALPHABET[d]).join(""); setInput(result); toast.success("已编码为 Base58"); }; // Decode const decode = () => { if (!input) return; const bytes = [0]; for (let i = 0; i < input.length; i++) { const c = input[i]; if (!(c in ALPHABET_MAP)) { toast.error("无效的 Base58 字符"); return; } for (let j = 0; j < bytes.length; j++) bytes[j] *= 58; bytes[0] += ALPHABET_MAP[c]; let carry = 0; for (let j = 0; j < bytes.length; ++j) { bytes[j] += carry; carry = bytes[j] >> 8; bytes[j] &= 0xff; } while (carry) { bytes.push(carry & 0xff); carry >>= 8; } } // Deal with leading zeros (represented by '1' in Base58 Bitcoin) for (let i = 0; i < input.length && input[i] === '1'; i++) bytes.push(0); const result = bytesToText(new Uint8Array(bytes.reverse())); setInput(result); toast.success("已解码为文本"); }; const clearAll = () => setInput(""); return (

Base58 编解码

比特币风格 Base58 文本转换

输入/输出文本