Software Engineering

Tips on how to Convert IPv4 to int32 in Javascript

Tips on how to Convert IPv4 to int32 in Javascript
Written by admin


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 are able to symbolize it because the 32 bit quantity: 2149583361.

Write a perform 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:

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

Possibility 2:

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

Possibility 3:

perform 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 resolution

describe("Exams", () => {
  it("check", () => {
    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")
  });
});

About the author

admin

Leave a Comment