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

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 20-Apr-2021 10:06:19
Advertisements