Easy methods to Convert IPv4 to int32 in Javascript

0
11
Adv1


Adv2

The problem

Take the next IPv4 handle: 128.32.10.1 This handle 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 handle has 32 bits, we will symbolize it because the 32 bit quantity: 2149583361.

Write a operate ipToInt32(ip) that takes an IPv4 handle and returns a 32 bit quantity.

  ipToInt32("128.32.10.1") => 2149583361

The answer in Javascript

Possibility 1:

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

Possibility 2:

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

Possibility 3:

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

Check instances to validate our answer

describe("Checks", () => {
  it("check", () => {
    Check.assertEquals(ipToInt32("128.32.10.1"),2149583361, "mistaken integer for ip: 128.32.10.1")
    Check.assertEquals(ipToInt32("128.114.17.104"),2154959208, "mistaken integer for ip: 128.114.17.104")
    Check.assertEquals(ipToInt32("0.0.0.0"),0, "mistaken integer for ip: 0.0.0.0")
  });
});
Adv3