Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
string ipaddress(int num){
char buffer[37];
sprintf(buffer, "%d.%d.%d.%d", (num>>24)&0xFF, (num>>16)&0xFF, (num>>8)&0xFF, (num&0xFF));
return string(buffer);
}
Here is Java code converting using strings
String stringIPAd = String.format("%1$08x", 2314105025L);
Integer First = Integer.parseInt(stringIPAd.substring(0,2),16);
Integer Second = Integer.parseInt(stringIPAd.substring(2,4),16);
Integer Third = Integer.parseInt(stringIPAd.substring(4,6),16);
Integer Fourth = Integer.parseInt(stringIPAd.substring(6,8),16);
System.out.print(First.toString()+".");
System.out.print(Second.toString()+".");
System.out.print(Third.toString()+".");
System.out.println(Fourth.toString());
Here is the approach I took in Java:
package myUtil;
import java.util.Random;
public class IpAddrToString {
public static String intIpToString (int ipAddr) {
StringBuilder ipAddrStr = new StringBuilder();
for (int i=1; i<=3; i++) {
ipAddrStr.insert(0, "." + String.valueOf(ipAddr & 0xFF));
ipAddr = ipAddr >> 8;
}
ipAddrStr.insert(0, String.valueOf(ipAddr & 0xFF));
return ipAddrStr.toString();
}
public static void main(String[] args) {
Random rand = new Random(System.currentTimeMillis());
int ipAddr = rand.nextInt();
System.out.println("The string IP for int [" + ipAddr + "] is [" + intIpToString(ipAddr) + "]");
}
}
Note: I elected to use ">>>" (shift in 0's on left side) instead of ">>" (shift in msb on left side) to keep things "clean", though in this case it does not matter (at least functionally, and I assume that ">>>" performs at least as well as ">>", but am not sure of that).
Sample test runs yield:
The string IP for int [262875931] is [15.171.43.27]
The string IP for int [647301379] is [38.149.9.3]
The string IP for int [-1484977025] is [167.125.12.127]
I believe that the negative value in the last example is simply a byproduct of all Java ints being signed.
- Anonymous July 30, 2013