Given a string representing of an IP address, such as "127.43.23.59", return a 32 bit integer representation of this string. The 32 bit integer is separated into four bytes, where each byte is one of the numbers in the string, separated by dots. If you & 0xFF with the returned integer, it should return 59. If you & 0xFF00 with the returned integer, it should return 23, etc.
public class IP{
public static void main(String[] args)
{
IP address = new IP();
int x = address.IPAddress("127.43.29.56");
}
public int IPAddress(String str)
{
int byte1 = 0;
int numbers[] = new int[4];
int index = 0;
int finalByte = 0;
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) != '.')
byte1 = 10*byte1 + (str.charAt(i) - 48);
else
{
numbers[index++] = byte1;
byte1 = 0;
}
}
numbers[index] = byte1;
return finalByte = (numbers[0]<<24) | (numbers[1]<<16)|
(numbers[2]<<8) | (numbers[3]);
}
}