IP-addresses stored as int results in overflow?

The result of the "<<" operator is always a signed, 32-bit integer, as per the spec.

When you shift back, use ">>>" to do an unsigned right shift.


Why is the converted IP negative?

It's NOT an overflow. The first part of your IP address is 192 which converts to 11000000 in binary. You then shift that all the way to the left. When there is a 1 in the leftmost position of a 32 bit number, it's negative.

How do you convert back to a string?

Do the same thing you did to convert from a string but in reverse. Shift right (and mask)!

function intToIP(int) {
    var part1 = int & 255;
    var part2 = ((int >> 8) & 255);
    var part3 = ((int >> 16) & 255);
    var part4 = ((int >> 24) & 255);

    return part4 + "." + part3 + "." + part2 + "." + part1;
}

Why reinvent the wheel? From Google:

OR, you can use what I found here:
http://javascript.about.com/library/blipconvert.htm

function dot2num(dot) 
{
    var d = dot.split('.');
    return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]);
}

function num2dot(num) 
{
    var d = num%256;
    for (var i = 3; i > 0; i--) 
    { 
        num = Math.floor(num/256);
        d = num%256 + '.' + d;
    }
    return d;
}

Tags:

Javascript