Last active
May 31, 2023 07:46
-
-
Save logbon72/1195a5d764fb4b5d72f74c1a718dba57 to your computer and use it in GitHub Desktop.
BigQuery UDF Convert Bytes to Hex & Hex to UUID
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
CREATE TEMP FUNCTION BytesToUUID(data BYTES) | |
RETURNS STRING | |
LANGUAGE js AS """ | |
const tableStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
const atob = function (base64) { | |
if (/(=[^=]+|={3,})$/.test(base64)) throw new Error("String contains an invalid character"); | |
base64 = base64.replace(/=/g, ""); | |
var n = base64.length & 3; | |
if (n === 1) throw new Error("String contains an invalid character"); | |
for (var i = 0, j = 0, len = base64.length / 4, bin = []; i < len; ++i) { | |
var a = tableStr.indexOf(base64[j++] || "A"), b = tableStr.indexOf(base64[j++] || "A"); | |
var c = tableStr.indexOf(base64[j++] || "A"), d = tableStr.indexOf(base64[j++] || "A"); | |
if ((a | b | c | d) < 0) throw new Error("String contains an invalid character"); | |
bin[bin.length] = ((a << 2) | (b >> 4)) & 255; | |
bin[bin.length] = ((b << 4) | (c >> 2)) & 255; | |
bin[bin.length] = ((c << 6) | d) & 255; | |
}; | |
return String.fromCharCode.apply(null, bin).substr(0, bin.length + n - 4); | |
}; | |
const base64ToHex = function(str) { | |
const raw = atob(str); | |
let result = ''; | |
for (let i = 0; i < raw.length; i++) { | |
const hex = raw.charCodeAt(i).toString(16); | |
result += (hex.length === 2 ? hex : '0' + hex); | |
} | |
return result.toLowerCase(); | |
} | |
//if all you need is the hex, skip the UUID below | |
const hex = base64ToHex(data); | |
//convert hex to UUID | |
return [ | |
hex.substring(0, 8), | |
hex.substring(8, 12), | |
hex.substring(12, 16), | |
hex.substring(16, 20), | |
hex.substring(20) | |
].join('-') | |
"""; | |
SELECT BytesToUUID(FROM_BASE64('IFdkTmmzT92YkDYQiV/zmQ==')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This link on SO was very helpful: https://stackoverflow.com/questions/23190056/hex-to-base64-converter-for-javascript/41797377