Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active September 28, 2015 10:08
Show Gist options
  • Save softwarespot/56d719674fc70fe2cf1c to your computer and use it in GitHub Desktop.
Save softwarespot/56d719674fc70fe2cf1c to your computer and use it in GitHub Desktop.
Kata
function binaryToString(binary) {
// Split for readability, though it could be in-lined too
const binaryToInteger = (string) => {
let final = 0;
for (let i = string.length - 1, digits = string.split(''), exp = 1; i >= 0; i--) {
final += +digits[i] * exp;
// Bit shift left by 1 i.e. 1, 2, 4, 8, 16, 32, 64....
exp <<= 1;
}
return final;
};
// Split into 8bit chunks and map to an array that is then joined
return binary === '' ? binary : binary.match(/([01]{8})/g).map((chunk) => {
return String.fromCharCode(binaryToInteger(chunk));
// Join to make a string
}).join('');
}
// Example
console.log(binaryToString('01100001'), 'a');
function ipToNum(ip) {
// Readability only!
const BINARY_LENGTH = 8;
return parseInt(ip.split('.').map((segment) => {
// +segment is a trick to parse as an integer
const binary = (+segment).toString(2);
// Ensure the length is 8 bits (leading zeros are stripped basically)
return new Array(BINARY_LENGTH - binary.length + 1).join('0') + binary;
}).join(''), 2); // 2 equals from binary
}
function numToIp(num) {
// Readability only!
const BINARY_LENGTH = 32;
// Sometimes this returns 31 bits or less and NOT 32 bits (leading zeros are stripped basically), so we have to pre-append zeros
num = num.toString(2);
return (new Array(BINARY_LENGTH - num.length + 1).join('0') + num).match(/[01]{8}/g).map((segment) => {
return parseInt(segment, 2).toString(10); // 2 equals from binary to decimal (10)
}).join('.');
}
// Example
console.log(ipToNum('192.168.1.1'));
console.log(numToIp(ipToNum('192.168.1.1')));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment