Skip to content

Instantly share code, notes, and snippets.

@shanewholloway
Last active June 19, 2018 22:49
Show Gist options
  • Save shanewholloway/0637678e322ff9fb38315a74c626c89a to your computer and use it in GitHub Desktop.
Save shanewholloway/0637678e322ff9fb38315a74c626c89a to your computer and use it in GitHub Desktop.
ArrayBuffer to Base64 packing and unpacking
const _fromCharCode = String.fromCharCode
export function pack_base64(arr) {
let res=''
const u8 = new Uint8Array(arr.buffer || arr)
const len = u8.byteLength
for (let i=0; i<len; i++)
res += _fromCharCode(u8[i])
return window.btoa(res)
}
const _charCodeAt = ''.charCodeAt
export function unpack_base64(str_b64) {
const sz = window.atob(str_b64)
const len = sz.length
const res = new Uint8Array(len)
for (let i=0; i<len; i++)
res[i] = _charCodeAt.call(sz, i)
return res
}
function test(count=1, width=64) {
if (0 > width) width = 0 | 1 - width * Math.random()
while (--count > 0) {
const b0 = new Uint8Array(width)
window.crypto.getRandomValues(b0)
const sz_b64 = pack_base64(b0)
const b1 = unpack_base64(sz_b64)
const b2 = Array.from(b0, (v,i) => ((b1[i] - v) || ''))
console.log(b2.join('.'))
}
}
console.log()
test(10, 63)
console.log()
test(10, 64)
console.log()
test(10, 65)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment