Wednesday, February 21, 2024
HomeSoftware EngineeringHow one can Convert IPv4 to int32 in Javascript

How one can Convert IPv4 to int32 in Javascript


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 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.break up(".").scale back(operate(int,v){ return int*256 + +v } )
}

Possibility 2:

operate ipToInt32(ip){
    ip = ip.break 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.break up('.').reverse().map(Quantity))
  var array32 = new Uint32Array(array8.buffer);
  return array32[0];
}

Check instances to validate our resolution

describe("Assessments", () => {
  it("check", () => {
    Check.assertEquals(ipToInt32("128.32.10.1"),2149583361, "incorrect integer for ip: 128.32.10.1")
    Check.assertEquals(ipToInt32("128.114.17.104"),2154959208, "incorrect integer for ip: 128.114.17.104")
    Check.assertEquals(ipToInt32("0.0.0.0"),0, "incorrect integer for ip: 0.0.0.0")
  });
});
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments