HomeSoftware EngineeringFind out how to Convert IPv4 to int32 in Javascript

# Find out how to Convert IPv4 to int32 in Javascript

## The problem#

Take the next IPv4 deal with: 128.32.10.1 This deal with has 4 octets the place every octet is a single byte (or 8 bits).

• 1st octet 128 has the binary illustration: 10000000
• 2nd octet 32 has the binary illustration: 00100000
• third octet 10 has the binary illustration: 00001010
• 4th octet 1 has the binary illustration: 00000001

So 128.32.10.1 == 10000000.00100000.00001010.00000001

As a result of the above IP deal with has 32 bits, we will characterize it because the 32 bit quantity: 2149583361.

Write a operate `ipToInt32(ip)`Â that takes an IPv4 deal with and returns a 32 bit quantity.

``````  ipToInt32("128.32.10.1") => 2149583361
``````

Choice 1:

``````operate ipToInt32(ip){
return ip.cut up(".").scale back(operate(int,v){ return int*256 + +v } )
}
``````

Choice 2:

``````operate ipToInt32(ip){
ip = ip.cut up('.');
return  ((ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + (ip[3] << 0))>>>0;
}
``````

Choice 3:

``````operate ipToInt32(ip){
var array8 = new Uint8Array(ip.cut up('.').reverse().map(Quantity))
var array32 = new Uint32Array(array8.buffer);
return array32[0];
}
``````

## Check circumstances to validate our resolution#

``````describe("Exams", () => {
it("take a look at", () => {
Check.assertEquals(ipToInt32("128.32.10.1"),2149583361, "improper integer for ip: 128.32.10.1")
Check.assertEquals(ipToInt32("128.114.17.104"),2154959208, "improper integer for ip: 128.114.17.104")
Check.assertEquals(ipToInt32("0.0.0.0"),0, "improper integer for ip: 0.0.0.0")
});
});
``````
RELATED ARTICLES