Riverbed Interview Question
Software Engineer / DevelopersCountry: United States
Seems like a clever solution. Is it guaranteed to be portable? I don't really use unions (most people don't, I think), so I don't know what exact guarantees they provide. Could some machine or compiler, for instance, decide to make the union more than 4 bytes and have the bytes of the int not line up with the bytes of the char[]?
well implementation of unions are standard over by all compliers (as far as I know)even the kernel(linux) uses it a lot.
public String getIPAddress(int IPAddress) {
if(IPAddress < 0) return null;
int fourth = IPAddress % 256;
IPAddress = IPAddress / 256;
int third = IPAddress % 256;
IPAddress = IPAddress / 256;
int second = IPAddress % 256;
int first = IPAddress / 256;
return String.format("%d.%d.%d.%d", first, second, third, fourth);
}
(Sorry, not very comfortable with C/C++ :()
char * get_ip_address(int ip_address)
{
unsigned int ip = (unsigned int) ip_address;
char* bytes = (char*) malloc(4*sizeof(*bytes));
bytes[0] = (char) (ip_address >> 24);
bytes[1] = (char) (ip_address >> 16);
bytes[2] = (char) (ip_address >> 8);
bytes[3] = (char) ip_address;
return bytes;
}
This would really take an unsigned int and return an unsigned char* if I got to pick...
@eugene.yarovoi: Your method doesn't "basically convert input ip_address to user-friendly format a.b.c.d" as asked in the question.
Fair enough. I supposed getting the bytes was the important part. How's this:
char * get_ip_address(int ip_address)
{
unsigned char bytes[4];
bytes[0] = (unsigned char) (ip_address >> 24);
bytes[1] = (unsigned char) (ip_address >> 16);
bytes[2] = (unsigned char) (ip_address >> 8);
bytes[3] = (unsigned char) ip_address;
//up to 3 chars for 4 groups of digits, 3 dots, and 1 null char
char* out = (char*) malloc((3*4+3+1)*sizeof(*out));
sprintf (out, "%u.%u.%u.%u", bytes[0], bytes[1], bytes[2], bytes[3]);
return out;
}
i don't think it works.
suppose the input is 192168110. the output should be 192.168.1.10 but not 0.192.168.110.
you are assuming that the given ip is already in a (4 x 3-digits = 12 digits) format. but i don't think this is the intention of the interviewer: otherwise they could just ask you to separate a 12-digit int.
No. That's not what this code is even supposed to do. 192168110 won't become 0.192.168.110 with my code, nor is 192.168.1.10 the right answer. The 4 bytes of the IP address are packed into the int, not just stored as back-to-back decimal digits.
here is an intelligent way(i guess..:P) to do it: I hope this helps!
#include<stdio.h>
- raja roy January 15, 2012