This address has 4 octets where each octet is a single byte (or 8 bits).
Because the above IP address has 32 bits, we can represent it as the unsigned 32 bit number: 2149583361
Complete the function that takes an unsigned 32 bit number and returns a string representation of its IPv4 address.
Examples
2149583361 – "128.32.10.1"
32 – "0.0.0.32"
0 – "0.0.0.0"
I tried to implement this way. It works on some tests, but for example, the program crashes on the number 1069972272 (because it starts translating everything from the beginning, not the end). How can I fix this program? I know it can be easier, but I would like to finish my version
function int32ToIp(int32){
let binaryNumber = int32.toString(2);
let buffer = [];
let result = [];
let i = 8;
for (let index = 0; index < 4; index++) {
buffer[index] = binaryNumber.slice(i - 8,i);
i += 8;
if(!buffer[index]) {
buffer[index] = '0';
}
}
for (let i = 0; i < buffer.length; i++) {
result[i] = parseInt(buffer[i], 2);
}
return result.toString().replace(/,/g, '.');
}
>Solution :
You need to left-pad the binary string with leading zeroes so that it is always 32 characters in length otherwise your code to extract the octet values doesn’t work.
For example:
function int32ToIp(int32) {
let binaryNumber = int32.toString(2).padStart(32, '0');
let buffer = [];
let result = [];
let i = 8;
for (let index = 0; index < 4; index++) {
buffer[index] = binaryNumber.slice(i - 8, i);
i += 8;
if (!buffer[index]) {
buffer[index] = '0';
}
}
for (let i = 0; i < buffer.length; i++) {
result[i] = parseInt(buffer[i], 2);
}
return result.toString().replace(/,/g, '.');
}
console.log(int32ToIp(2149583361), 'expect', '128.32.10.1');
console.log(int32ToIp(1069972272), 'expect', '63.198.123.48');
Nice