Home  >  Article  >  Web Front-end  >  Convert unsigned 32-bit decimal to corresponding ipv4 address in JavaScript

Convert unsigned 32-bit decimal to corresponding ipv4 address in JavaScript

WBOY
WBOYforward
2023-09-07 08:01:111302browse

在 JavaScript 中将无符号 32 位十进制转换为相应的 ipv4 地址

Question

Consider the following ipv4 address -

128.32.10.1

If we convert it to binary, the equivalent is -

10000000.00100000.00001010.00000001

Additionally, if we convert this binary to unsigned 32-bit decimal, the decimal will be -

2149583361

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

We need to write a JavaScript function that accepts a 32-bit unsigned integer and returns its equivalent ipv4 address.

Example

The following is the code-

Real-time demonstration

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

Output

The following is the console output-

128.32.10.1

The above is the detailed content of Convert unsigned 32-bit decimal to corresponding ipv4 address in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete