Created
November 29, 2021 15:42
-
-
Save manthrax/96f5edadabe2da3ec39d94e807eaf096 to your computer and use it in GitHub Desktop.
Uint8Array to hex string.. and back... and some tests....
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let b2h = [] | |
for(let i=0;i<256;i++)b2h[i]=i.toString(16).padStart(2,"0") | |
let arrayToHex=(a)=>{ | |
let hex = new Array(a.length) | |
for(let i=0,l=a.length;i<l;i++)hex[i]=b2h[a[i]] | |
return hex.join('') | |
} | |
let h2b = {} | |
for(let i=0;i<256;i++)h2b[i.toString(16).padStart(2,"0")]=i; | |
let splitHex = new RegExp('.{1,' + 2 + '}', 'g'); | |
let hexToArray=(hex)=>{ | |
hex = hex.match(splitHex); | |
let a = new Uint8Array(hex.length) | |
for(let i=0,l=a.length;i<l;i++)a[i]=h2b[hex[i]] | |
return a | |
} | |
//Test: Convert a Uint8Array to hex and back | |
let mu = new Uint8Array([123,234,125,255]) | |
let hex = arrayToHex(mu) | |
let out = hexToArray(hex) | |
console.log(mu, " converts to: ", hex, " decodes to:", out) | |
let base64test="MOfmaofmosd"; | |
let arr = btoa( base64test ) | |
let res = atob(arr); | |
console.log(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment