Last active
November 5, 2024 08:56
-
-
Save jppommet/5708697 to your computer and use it in GitHub Desktop.
javascript conversion from ip address to long integer and vice versa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function int2ip (ipInt) { | |
return ( (ipInt>>>24) +'.' + (ipInt>>16 & 255) +'.' + (ipInt>>8 & 255) +'.' + (ipInt & 255) ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ip2int(ip) { | |
return ip.split('.').reduce(function(ipInt, octet) { return (ipInt<<8) + parseInt(octet, 10)}, 0) >>> 0; | |
} |
Would it not be shorter then to to replace <<8
with * 256
?
It seems like the >>> 0
is then obsolete.
'192.168.0.230'.split('.').reduce(function(ipInt, octet) { return (ipInt * 256) + parseInt(octet, 10)}, 0);
// 3232235750
@elovin indeed, it is!
My example was to explain the difference between the two methods because someone was confused with the negative value being incorrect, which I demonstrated is not true. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The methods do work correctly.
-1062731546
as well as3232235750
are a correct integer representation of the IP address192.168.0.230
. In binary, they're the exact same, but depending on whether you look at the value as signed integer (then the first bit means "negative value" and the remaining 31 bits mean 1062731546) or unsigned (then the 32 bits mean 3232235750).>>> 0
in theip2int
function ensures a conversion to unsigned int. Removing it turns the result into the negative value you were looking for: