Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript base2 to base64

const encode = bitstr => {
  const bytes = [];
  // convert bit string to BigInt
  let value = BigInt('0b' + bitstr);
  // chop it up into bytes
  while (value > 0n) {
    bytes.unshift(Number(value & 0xffn));
    value >>= 8n;
  }
  // convert to binary string and encode as base64
  return btoa(String.fromCharCode.apply(null, bytes));
};

const decode = b64 => {
  // decode base64 to binary string
  const bstr = atob(b64);
  // convert binary string to bit string
  return new Array(bstr.length).fill(0).map(
    (_,i) => bstr.charCodeAt(i).toString(2).padStart(8, i ? '0' : '')
  ).join('');
};

const bitstr = '100110110101000110100011011001100010110100011011001100100110100011000001100000110000011000001100001001010100111110000011001111100101010011111010011100010110001001001001100000110100111010010100111110000111001000100000110001001000101100111110011001001001101011010001011001001101001010000011000100100100110000011010011';
const encoded = encode(bitstr);
const decoded = decode(encoded);

console.log(bitstr);
console.log(encoded);
console.log(decoded);
 Run code snippetHide results
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #javascript
ADD COMMENT
Topic
Name
1+3 =