deno.com

Hex 和 base64 编码

在 Github 上编辑

在某些情况下,在不同的字符串和数组缓冲区格式之间进行编码和解码是很有用的。Deno 标准库使这变得容易。

标准库提供了 hex 和 base64 编码和解码实用程序
import { decodeBase64, encodeBase64 } from "jsr:@std/encoding/base64";
import { decodeHex, encodeHex } from "jsr:@std/encoding/hex";
我们可以使用 encodeBase64 方法轻松地将字符串或数组缓冲区编码为 base64。
const base64Encoded = encodeBase64("somestringtoencode");
console.log(encodeBase64(new Uint8Array([1, 32, 67, 120, 19])));
然后,我们可以使用 decode 方法将 base64 解码为 Uint8Array。
const base64Decoded = decodeBase64(base64Encoded);
如果我们想将值作为字符串获取,我们可以使用内置的 TextDecoder。
const textDecoder = new TextDecoder();
console.log(textDecoder.decode(base64Decoded));
要编码 hex,我们可以使用 encodeHex 方法。
const hexEncoded = encodeHex("somestringtoencode");
console.log(hexEncoded);
我们可以使用 decodeHex 方法转换回字符串。
const hexDecoded = decodeHex(hexEncoded);
console.log(textDecoder.decode(hexDecoded));

使用 Deno CLI 在本地运行 此示例

deno run https://docs.deno.org.cn/examples/scripts/hex_base64_encoding.ts

您找到所需的内容了吗?

隐私政策