31 lines
806 B
TypeScript
31 lines
806 B
TypeScript
export function bytesToBase64(bytes: Uint8Array): string {
|
|
let binary = ''
|
|
bytes.forEach((b) => {
|
|
binary += String.fromCharCode(b)
|
|
})
|
|
return globalThis.btoa(binary)
|
|
}
|
|
|
|
export function base64ToBytes(value: string): Uint8Array {
|
|
const binary = globalThis.atob(value)
|
|
const bytes = new Uint8Array(binary.length)
|
|
for (let i = 0; i < binary.length; i += 1) {
|
|
bytes[i] = binary.charCodeAt(i)
|
|
}
|
|
return bytes
|
|
}
|
|
|
|
export function bytesToHex(bytes: Uint8Array): string {
|
|
return Array.from(bytes)
|
|
.map((b) => b.toString(16).padStart(2, '0'))
|
|
.join('')
|
|
}
|
|
|
|
export function hexToBytes(hexString: string): Uint8Array {
|
|
const parts = hexString.match(/.{1,2}/g)
|
|
if (!parts) {
|
|
return new Uint8Array([])
|
|
}
|
|
return new Uint8Array(parts.map((part) => Number.parseInt(part, 16)))
|
|
}
|