Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Converting an unsigned 32 bit decimal to corresponding ipv4 address in JavaScript
Converting a 32-bit unsigned integer to an IPv4 address involves extracting the four bytes that represent each octet of the IP address. Each IPv4 address consists of four octets (0-255), which can be extracted using bitwise operations.
Understanding the Problem
Consider the IPv4 address:
128.32.10.1
When converted to binary, each octet becomes an 8-bit binary number:
10000000.00100000.00001010.00000001
Combining these four 8-bit segments creates a 32-bit binary number, which equals the decimal value:
2149583361
Our task is to reverse this process: convert the 32-bit unsigned integer back to its IPv4 address format.
Solution Using Bitwise Operations
The most efficient approach uses bitwise right shift (>>>) and bitwise AND (&) operations to extract each byte:
const num = 2149583361;
const int32ToIp = (num) => {
return (num >>> 24 & 0xFF) + '.' +
(num >>> 16 & 0xFF) + '.' +
(num >>> 8 & 0xFF) + '.' +
(num & 0xFF);
};
console.log(int32ToIp(num));
console.log(int32ToIp(0)); // Edge case: all zeros
console.log(int32ToIp(4294967295)); // Edge case: all 255s
128.32.10.1 0.0.0.0 255.255.255.255
How the Algorithm Works
The conversion process extracts each 8-bit segment from the 32-bit integer:
-
num >>> 24 & 0xFF: Extracts bits 24-31 (first octet) -
num >>> 16 & 0xFF: Extracts bits 16-23 (second octet) -
num >>> 8 & 0xFF: Extracts bits 8-15 (third octet) -
num & 0xFF: Extracts bits 0-7 (fourth octet)
The 0xFF mask (255 in decimal) ensures only the lowest 8 bits are kept after each shift operation.
Alternative Implementation
Here's a more readable version that breaks down the process:
const convertToIPv4 = (num) => {
const byte1 = (num >>> 24) & 0xFF;
const byte2 = (num >>> 16) & 0xFF;
const byte3 = (num >>> 8) & 0xFF;
const byte4 = num & 0xFF;
return `${byte1}.${byte2}.${byte3}.${byte4}`;
};
console.log(convertToIPv4(2149583361));
console.log(convertToIPv4(3232235777)); // 192.168.1.1
128.32.10.1 192.168.1.1
Key Points
- Use unsigned right shift (
>>>) to avoid sign extension issues - The
0xFFmask extracts exactly 8 bits for each octet - IPv4 addresses range from 0.0.0.0 to 255.255.255.255
- Each octet must be between 0 and 255
Conclusion
Converting a 32-bit unsigned integer to IPv4 format requires extracting four 8-bit segments using bitwise operations. The unsigned right shift and AND operations provide an efficient solution for this common networking task.
