Skip to content

Instantly share code, notes, and snippets.

@SimonSimCity
Created March 29, 2017 07:56
Show Gist options
  • Save SimonSimCity/8795abe6e0d15941b85dbe95f81020ad to your computer and use it in GitHub Desktop.
Save SimonSimCity/8795abe6e0d15941b85dbe95f81020ad to your computer and use it in GitHub Desktop.
Takes an 8-bit string and encodes it to a 7-bit string (base64 compatible). Doesn't work with characters upover the 8th bit ...
const id = Random.id();
const bitEncode = (s) => {
let binString = '';
for (let i = 0; i < s.length; i++) {
const bin = (s.charCodeAt(i) - 20).toString(2);
const binSubString = (`0000000000${bin}`).slice(-7);
binString += binSubString;
}
let result = '';
const binArray = binString.match(/.{1,8}/g);
for (let i = 0; i < binArray.length; i++) {
const binSubString = (`${binArray[i]}00000000`).substring(0, 8);
const hex = parseInt(binSubString, 2).toString(16);
const hexSubString = (`0${hex}`).slice(-2);
result += `${hexSubString}`;
}
return result;
};
console.log(`UUID-representation: ${bitEncode(id)}`);
const bitDecode = (s) => {
const hexes = s.match(/.{1,2}/g) || [];
let back = '';
let binString = '';
for (let j = 0; j < hexes.length; j++) {
const bin = parseInt(hexes[j], 16).toString(2);
const binSubString = (`00000000${bin}`).slice(-8);
binString += binSubString;
}
const binArray = binString.match(/.{1,7}/g);
for (let j = 0; j < binArray.length; j++) {
const binSubString = binArray[j];
back += String.fromCharCode(parseInt(binSubString, 2) + 20);
}
return back;
};
console.log(`And back: ${bitDecode(bitEncode(id))}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment