Skip to content

Instantly share code, notes, and snippets.

@mpr0xy
Created March 14, 2018 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpr0xy/2ca31600e54b01ce26a4e1c216c5939c to your computer and use it in GitHub Desktop.
Save mpr0xy/2ca31600e54b01ce26a4e1c216c5939c to your computer and use it in GitHub Desktop.
function ip(str) {
var length = str.length;
var ans = 0;
var stack = [];
var step = 0;
var lastStep = 0;
var lastchar = ''
// 处理每一次位移
function handle() {
if (stack.length === 0) {
if (lastchar === 'b') {
ans = ans | (1 << (32 - step - 1));
}
step++;
} else {
var nStep = 0;
stack.forEach(function(item, index) {
nStep += item * Math.pow(10, (stack.length - 1 - index))
});
if (lastchar === 'b') {
ans = ans | ((Math.pow(2, nStep) - 1) << (32 - step - nStep))
}
step += nStep;
}
}
for (var i = 0; i < length; i++) {
// 每次处理一次变更
if (str[i] === 'a' || str[i] === 'b') {
lastchar = str[i];
handle();
stack = [];
} else {
stack.push(Number(str[i]));
}
}
var a = ans >> 24;
var b = (ans >> 16) & (Math.pow(2, 8) - 1);
var c = (ans >> 8) & (Math.pow(2, 8) - 1);
var d = ans & (Math.pow(2, 8) - 1);
if (a === -1) {
a = 255;
}
return a + '.' + b + '.' + c + '.' + d;
}
var ans = ip('7ab7ab7a2b6ab');
console.log(ans);
console.log(ans === '1.1.1.129');
var ans = ip('32a');
console.log(ans);
var ans = ip('32b');
console.log(ans);
var ans = ip('8b8a8b8a');
console.log(ans);
var ans = ip('a7b8a8a7ab');
console.log(ans);
var ans = ip('aa6baa6baa6b8a');
console.log(ans);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment