The challenge
Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits).
- 1st octet 128 has the binary representation: 10000000
- 2nd octet 32 has the binary representation: 00100000
- 3rd octet 10 has the binary representation: 00001010
- 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361.
Write a function ipToInt32(ip)
that takes an IPv4 address and returns a 32 bit number.
ipToInt32("128.32.10.1") => 2149583361
The solution in Javascript
Option 1:
function ipToInt32(ip){
return ip.split(".").reduce(function(int,v){ return int*256 + +v } )
}
Option 2:
function ipToInt32(ip){
ip = ip.split('.');
return ((ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + (ip[3] << 0))>>>0;
}
Option 3:
function ipToInt32(ip){
var array8 = new Uint8Array(ip.split('.').reverse().map(Number))
var array32 = new Uint32Array(array8.buffer);
return array32[0];
}
Test cases to validate our solution
describe("Tests", () => {
it("test", () => {
Test.assertEquals(ipToInt32("128.32.10.1"),2149583361, "wrong integer for ip: 128.32.10.1")
Test.assertEquals(ipToInt32("128.114.17.104"),2154959208, "wrong integer for ip: 128.114.17.104")
Test.assertEquals(ipToInt32("0.0.0.0"),0, "wrong integer for ip: 0.0.0.0")
});
});