Last active
December 24, 2020 06:09
-
-
Save iwill/72720c283edda83ce83ecc799b06225d to your computer and use it in GitHub Desktop.
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
| Base64 = { | |
| // @param n Number, 6 bits, e.g. 0b111111 | |
| // @return String, a char, e.g. "/" | |
| encode6Bits: function(n) { | |
| n = Math.min(Math.max(0, n), 63); | |
| if (n >= 0 && n <= 25) return String.fromCharCode("A".charCodeAt(0) + n); // ["A", "Z"] | |
| else if (n >= 26 && n <= 51) return String.fromCharCode("a".charCodeAt(0) + n - 26); // ["a", "z"] | |
| else if (n >= 52 && n <= 61) return String.fromCharCode("0".charCodeAt(0) + n - 52); // ["0", "9"] | |
| else if (n == 62) return "+"; | |
| else /* if (n == 63) */ return "/"; | |
| }, | |
| // @param c Number, char code, e.g. 47 | |
| // @return Number, 6 bits, e.g. 0b111111 | |
| decode6Bits: function(c) { // c: charCode | |
| if (c >= "A".charCodeAt(0) && c <= "Z".charCodeAt(0)) return c - "A".charCodeAt(0); // [ 0, 25] | |
| else if (c >= "a".charCodeAt(0) && c <= "z".charCodeAt(0)) return c - "a".charCodeAt(0) + 26; // [26, 51] | |
| else if (c >= "0".charCodeAt(0) && c <= "9".charCodeAt(0)) return c - "0".charCodeAt(0) + 52; // [52, 61] | |
| else if (c == "+".charCodeAt(0)) return 62; | |
| else /* if (c == "/".charCodeAt(0)) */ return 63; | |
| }, | |
| // @param bits64 BigInt, 64 bits, e.g. 0xFFFFFFFFFFFFFFFFn | |
| // @return String, 1 ~ 11 chars, e.g. "//////////P" | |
| encode64Bits: function(bits64) { | |
| let base64 = ""; | |
| while (bits64) { | |
| base64 += this.encode6Bits(Number(bits64 & 0b111111n)); // 0b111111: 6 bits | |
| bits64 >>= 6n; | |
| } | |
| return base64 || "A"; | |
| }, | |
| // @param base64 String, 1 ~ 11 chars, e.g. "//////////P" | |
| // @return BigInt, 64 bits, e.g. 0xFFFFFFFFFFFFFFFFn | |
| decode64Bits: function(base64) { | |
| let length = Math.min(base64.length, 11); // 11: 64 bits ~= 11 chars * 6 bits | |
| let bits64 = 0n; | |
| for (let i = 0; i < length; ++i) { | |
| let bits06 = this.decode6Bits(base64.charCodeAt(i)); | |
| bits64 |= BigInt(bits06) << BigInt(6 * i); | |
| } | |
| return bits64; | |
| } | |
| }; | |
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
| BigInt.max = function(a, b) { | |
| return a > b ? a : b; | |
| }; | |
| BigInt.min = function(a, b) { | |
| return a < b ? a : b; | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.