julesbou julesbou - 4 months ago 12
Javascript Question

how to convert an array to the shortest string possible

I have following array (i'm using JavaScript):

var arr = [2, 0, 0, 0, 12]


(Each element of the array can be between
0
to
15
. Length is fixed, 5 elements.)


I want to convert this array to the shortest string possible. My actual solution is to convert it to an hexadecimal (base16) string:

var str = '2000c'


Is there a better solution? (I'm looking for a solution in JavaScript, without any library if possible)

Answer

Your input is 5 * 4 bits = 20 bits. You can recode your array as a 3-character string (24 bits with an actual payload of 20 bits) and encode it with btoa() to produce a 4-character printable string.

function pack(arr) {
  return btoa(
    String.fromCharCode((arr[1] << 4) | arr[0]) +
    String.fromCharCode((arr[3] << 4) | arr[2]) +
    String.fromCharCode(arr[4])
  );
}

var packed = pack([2, 0, 0, 0, 12]);

console.log(packed); // output: 'AgAM'

The unpacking function would use atob() and rebuild the original array like that:

function unpack(packed) {
  var str = atob(packed);
  
  return [
    str.charCodeAt(0) & 0xf,
    str.charCodeAt(0) >> 4,
    str.charCodeAt(1) & 0xf,
    str.charCodeAt(1) >> 4,
    str.charCodeAt(2)
  ];
}

var unpacked = unpack('AgAM');

console.log(unpacked); // output: [ 2, 0, 0, 0, 12 ]