DEV Community

Vibhor Singh
Vibhor Singh

Posted on

int32 to IPv4

As you can see in the below screenshot, it has the problem description and what the input and output are supposed to be -

Problem description and examples of input and output screenshot

The input would be an integer e.g.

2149583361

The output must be in IPv4 format e.g.

"128.32.10.1"

The programming language used here is Javascript but you can use any language of your choice.

Approach -

  • Convert the decimal integer to its binary representation
  • Convert the binary form to its 32 bit form
  • Divide the 32 bits into 8 bits each and store them in an array
  • Convert all 8 binary bits to its decimal form
  • Store them as a string

The steps would be -

  • Take a variable and store the input in it

let int32="2149583361";

  • Take another variable and convert the input from decimal to binary using Javascript's inbuilt toString() method and providing it the parameter 2 to convert the decimal integer to its binary string

let s=int32.toString(2);

  • Take an empty variable and store 0's in it of length => 32-(length of string)
let zero_s="";
  let temp=32-s.length;
  for(let i=0;i<temp;i++) 
    zero_s+="0";
Enter fullscreen mode Exit fullscreen mode
  • Take another variable and store the final 32 bits string by appending the zero bits string to the original input string

let res_s=zero_s+s;

  • Use a for loop to traverse through the 32 bit string and split them into 8 bits each part and store them in an array
let array=[];
  let z=0;
  for(let j=0;j<4;j++) {
    let r=res_s.substring(z, 8+z);
    array.push(r);
    z+=8;
  }
Enter fullscreen mode Exit fullscreen mode
  • Take another array to store the converted decimal strings element using Javascript's inbuilt parseInt() method
let array2=[];
  for(let k of array) {
    let qq=parseInt(k, 2);
    array2.push(qq);
  }
Enter fullscreen mode Exit fullscreen mode
  • Print the output by converting the array into a string using dots(.) to seperate them with the help of join() function

return array2.join(".");

This problem uses the concept of decimal to binary conversion and vice-versa.

It also jogs your memory to array to string conversion and vice-verse.

Top comments (0)