Private
ArrPrivate
codePrivate
lookupPrivate
revPrivate
_byte这是一个私有方法,用于计算 Base64 字符串解码后的字节数组长度。
在下面的示例中,我们首先将字符串编码为 Base64 字符串,然后使用 getLens 方法计算出有效长度和占位符长度。最后,我们使用 _byteLength 方法计算解码后的字节数组长度,并验证其结果是否正确。
const base64 = new Base64()
const str = 'Hello, world!'
const encoded = base64.fromByteArray(new TextEncoder().encode(str))
const [validLen, placeHoldersLen] = base64.getLens(encoded)
console.log(base64._byteLength(encoded, validLen, placeHoldersLen)) // 12
Base64 字符串
Base64 字符串的有效字符长度
Base64 字符串的占位符长度
解码后的字节数组长度
Private
byte这是一个私有方法,用于计算 Base64 字符串解码后的字节数组长度。
在下面的示例中,我们首先将字符串编码为 Base64 字符串,然后使用 byteLength 方法计算解码后的字节数组长度,并验证其结果是否正确。
const base64 = new Base64()
const str = 'Hello, world!'
const encoded = base64.fromByteArray(new TextEncoder().encode(str))
console.log(base64.byteLength(encoded)) // 12
Base64 字符串
解码后的字节数组长度
Private
encode这是一个私有方法,用于将字节数组中的一段数据编码成 Base64 字符串。
在下面的示例中,我们首先将字符串编码为 Base64 字符串,然后使用 encodeChunk 方法将其编码成 Base64 字符串,并验证其结果是否正确。
const base64 = new Base64()
const str = 'Hello, world!'
const encoded = base64.fromByteArray(new TextEncoder().encode(str))
console.log(base64.encodeChunk(encoded, 0, encoded.length)) // "SGVsbG8sIHdvcmxkIQ=="
Uint8Array 数组或者常规数组
起始位置
结束位置
编码后的 Base64 字符串
这是一个公共方法,用于将字节数组编码为 Base64 字符串。
在下面的示例中,我们首先将字符串编码为字节数组,然后使用 fromByteArray 方法将其编码成 Base64 字符串,并验证其结果是否正确。
const base64 = new Base64()
const str = 'Hello, world!'
const encoded = base64.fromByteArray(new TextEncoder().encode(str))
console.log(encoded) // "SGVsbG8sIHdvcmxkIQ=="
Uint8Array 数组或者常规数组
编码后的 Base64 字符串
Private
get这是一个私有方法,用于计算 Base64 字符串的有效长度和占位符长度。
该方法接受一个 Base64 字符串作为参数,并返回一个元组,包含 Base64 字符串的有效长度和占位符长度。如果 Base64 字符串长度不是 4 的倍数,则会抛出错误。
在 Base64 编码和解码中,由于末尾可能存在一到两个 "=" 符号,我们需要根据这些符号的位置计算出有效的编码字符长度并去除这些符号。此外,如果 Base64 字符串长度不是 4 的倍数,则需要添加占位符 "="。
在下面的示例中,我们首先将字符串编码为 Base64 字符串,然后使用 getLens 方法计算出有效长度和占位符长度。最后,我们使用 toByteArray 方法将 Base64 字符串解码为字节数组,并验证其长度是否正确。
const base64 = new Base64()
const str = 'Hello, world!'
const encoded = base64.fromByteArray(new TextEncoder().encode(str))
const [validLen, placeHoldersLen] = base64.getLens(encoded)
console.log(validLen) // 16
console.log(placeHoldersLen) // 0
const decoded = base64.toByteArray(encoded)
console.log(decoded.length) // 12
Base64 字符串
[有效长度, 占位符长度] 的元组
这是一个公共方法,用于将 Base64 字符串解码为字节数组。
在下面的示例中,我们首先将字符串编码为 Base64 字符串,然后使用 toByteArray 方法将其解码为字节数组,并验证其结果是否正确。
const base64 = new Base64()
const str = 'Hello, world!'
const encoded = base64.fromByteArray(new TextEncoder().encode(str))
console.log(base64.toByteArray(encoded)) // Uint8Array(12) [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
Base64 字符串
Uint8Array 数组
Private
triplet这是一个私有方法,用于将三个字节转换为四个 Base64 字符。
在下面的示例中,我们使用 tripletToBase64 方法将三个字节转换为四个 Base64 字符,并验证其结果是否正确。
const base64 = new Base64()
sole.log(base64.tripletToBase64((72 << 16) | (101 << 8) | 108)) // "SGVs"
三个字节组成的数字
四个 Base64 字符
Generated using TypeDoc
这是一个 Base64 编码和解码的类,可以将字节数组(Uint8Array 或 Array)转换为 Base64 字符串,也可以将 Base64 字符串解码为字节数组。
Example