Syntax error Converting an unsigned 32 bit decimal to corresponding ipv4 address in JavaScript

Converting an unsigned 32 bit decimal to corresponding ipv4 address in JavaScript



Problem

Consider the following ipv4 address −

128.32.10.1

If we convert it to binary, the equivalent will be −

10000000.00100000.00001010.00000001

And further if we convert this binary to unsigned 32 bit decimal, the decimal will be −

2149583361

Hence, we can say that the ipv4 equivalent of 2149583361 is 128.32.10.1

We are required to write a JavaScript function that takes in a 32-bit unsigned integer and returns its equivalent ipv4 address.

Example

Following is the code −

 Live Demo

const num = 2149583361;
const int32ToIp = (num) => {
   return (num >>> 24 & 0xFF) + '.' +
   (num >>> 16 & 0xFF) + '.' +
   (num >>> 8 & 0xFF) + '.' +
   (num & 0xFF);
};
console.log(int32ToIp(num));

Output

Following is the console output −

128.32.10.1
Updated on: 2021-04-20T06:37:34+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements