Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

int32 to IPv4 in javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
1 comments

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading