working with binary and base64 data

Solutions on MaxInterview for working with binary and base64 data by the best coders in the world

showing results for - "working with binary and base64 data"
Gabriela
30 Sep 2019
1//note:  it is assumed that the Base64 object has already been defined
2//License:  Apache 2.0
3Base64.byteToCharMap_ = null;
4Base64.charToByteMap_ = null;
5Base64.byteToCharMapWebSafe_ = null;
6Base64.charToByteMapWebSafe_ = null;
7Base64.ENCODED_VALS_BASE =
8    'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
9    'abcdefghijklmnopqrstuvwxyz' +
10    '0123456789';
11
12/**
13 * Our default alphabet. Value 64 (=) is special; it means "nothing."
14 * @type {string}
15 */
16Base64.ENCODED_VALS = Base64.ENCODED_VALS_BASE + '+/=';
17Base64.ENCODED_VALS_WEBSAFE = Base64.ENCODED_VALS_BASE + '-_.';
18
19/**
20 * Base64-encode an array of bytes.
21 *
22 * @param {Array.<number>|Uint8Array} input An array of bytes (numbers with
23 *     value in [0, 255]) to encode.
24 * @param {boolean=} opt_webSafe Boolean indicating we should use the
25 *     alternative alphabet.
26 * @return {string} The base64 encoded string.
27 */
28Base64.encodeByteArray = function(input, opt_webSafe) {
29  Base64.init_();
30
31  var byteToCharMap = opt_webSafe ?
32                      Base64.byteToCharMapWebSafe_ :
33                      Base64.byteToCharMap_;
34
35  var output = [];
36
37  for (var i = 0; i < input.length; i += 3) {
38    var byte1 = input[i];
39    var haveByte2 = i + 1 < input.length;
40    var byte2 = haveByte2 ? input[i + 1] : 0;
41    var haveByte3 = i + 2 < input.length;
42    var byte3 = haveByte3 ? input[i + 2] : 0;
43
44    var outByte1 = byte1 >> 2;
45    var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
46    var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6);
47    var outByte4 = byte3 & 0x3F;
48
49    if (!haveByte3) {
50      outByte4 = 64;
51
52      if (!haveByte2) {
53        outByte3 = 64;
54      }
55    }
56
57    output.push(byteToCharMap[outByte1],
58                byteToCharMap[outByte2],
59                byteToCharMap[outByte3],
60                byteToCharMap[outByte4]);
61  }
62
63  return output.join('');
64};
65
66/**
67 * Lazy static initialization function. Called before
68 * accessing any of the static map variables.
69 * @private
70 */
71Base64.init_ = function() {
72  if (!Base64.byteToCharMap_) {
73    Base64.byteToCharMap_ = {};
74    Base64.charToByteMap_ = {};
75    Base64.byteToCharMapWebSafe_ = {};
76    Base64.charToByteMapWebSafe_ = {};
77
78    // We want quick mappings back and forth, so we precompute two maps.
79    for (var i = 0; i < Base64.ENCODED_VALS.length; i++) {
80      Base64.byteToCharMap_[i] =
81          Base64.ENCODED_VALS.charAt(i);
82      Base64.charToByteMap_[Base64.byteToCharMap_[i]] = i;
83      Base64.byteToCharMapWebSafe_[i] =
84          Base64.ENCODED_VALS_WEBSAFE.charAt(i);
85      Base64.charToByteMapWebSafe_[
86          Base64.byteToCharMapWebSafe_[i]] = i;
87    }
88  }
89};
90