Skip to content

Instantly share code, notes, and snippets.

Last active September 12, 2023 04:10
  • Star 62 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
javascript conversion from ip address to long integer and vice versa
function int2ip (ipInt) {
return ( (ipInt>>>24) +'.' + (ipInt>>16 & 255) +'.' + (ipInt>>8 & 255) +'.' + (ipInt & 255) );
function ip2int(ip) {
return ip.split('.').reduce(function(ipInt, octet) { return (ipInt<<8) + parseInt(octet, 10)}, 0) >>> 0;
Copy link

filecage commented Mar 1, 2023

I've used both of your function, which converted "original_int -1062731546" to "converted ip"
Then I tried to reverse but it gave me "converted int 3232235750" instead of "-1062731546",
Here is the link to demo:

These methods don't work right, -1062731546 is correct, I'm just digging into this now, so I am not an expert, but anything over goes into the negative space for 32 bit and would set the negative bit. or something like that.

The methods do work correctly. -1062731546 as well as 3232235750 are a correct integer representation of the IP address 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 the ip2int function ensures a conversion to unsigned int. Removing it turns the result into the negative value you were looking for:

// 3232235750
''.split('.').reduce(function(ipInt, octet) { return (ipInt<<8) + parseInt(octet, 10)}, 0) >>> 0; 

// -1062731546
''.split('.').reduce(function(ipInt, octet) { return (ipInt<<8) + parseInt(octet, 10)}, 0);  

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment