Binary to base 64 encoding - Node.js String

Node.js examples for String:Base 64

Description

Binary to base 64 encoding

Demo Code


var ALPHABET = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","-","_"];

/**//w  w  w. j ava2  s .  c om
  binary: String
*/
function binaryToB64(n) {
  var b64String = '';
  while (n.length > 5) {
    // take last 6 bits, 2^6 = 64
    var last6Bits = n.substr(n.length - 6, 6);
    n = n.substr(0, n.length - 6);

    var decimalDigit = parseInt(last6Bits, 2);
    b64String = ALPHABET[decimalDigit] + b64String;
  }
  if (n.length > 0) {
    var decimalDigit = parseInt(n, 2);
    b64String = ALPHABET[decimalDigit] + b64String;
  }
  return b64String;
}

function binaryToDecimal(n) {
  return parseInt(n, 2);
}

function b64ToDecimal(n) {
  return parseInt(b64ToBinary(n), 2);
}

function b64ToBinary(n) {

  function prefixWithZeroes(digitString) {
    if (digitString.length === 6) {
      return digitString;
    } else if (digitString.length < 6) {
      var restZeroes = [
        '',
        '0',
        '00',
        '000',
        '0000',
        '00000'
      ];
      var rest = 6 - digitString.length;
      return restZeroes[rest] + digitString;
    }
  }

  if (typeof n !== 'string') {
    debugger
    throw new TypeError('the input argument `n` is not a string.');
  }

  var result = n.map(function(digit) {
    return prefixWithZeroes(ALPHABET.indexOf(digit).toString(2));
  });

  // IMPORTANT!!!
  // If the ID Space is eg. 8, then 4 leading zeroes are generated!
  // If its 160, 2 leading zeroes are generated.



  var padding = 6 - (constants.HASH_SPACE % 6);

  if (constants.HASH_SPACE % 6 === 0) {
    padding = padding - 6;
  }

  return result.substring(padding, result.length);
}


function getRandomBinarySequence(n) {
  var bits = '';
  for (var i = 0; i < n; i++) {
    var rand = Math.random();
    if (rand > 0.5) {
      bits += '1';
    } else {
      bits += '0';
    }
  }
  return bits;
}

var distance = function(a, b) {
  var aBin = b64ToBinary(a)
    , bBin = b64ToBinary(b);

  return aBin.xor(bBin);
}

/**
 * Sort an array of `ids` by the distance to `id`
 * @param  {Array} array
 * @param  {String} id
 * @param  {Boolean} desc (optional)
 * @return {Array}
 */
var sortByDistance = function(array, id, desc) {
  var sorting = !!desc;
  if (sorting) {
    return array.sort(function(a, b) {
      return distance(b, id) - distance(a, id);
    });
  } else {
    return array.sort(function(a, b) {
      return distance(a, id) - distance(b, id);
    });
  }
}

Related Tutorials