Eddy Freeman
Eddy Freeman

Reputation: 3309

using indexOf and substring to calculate a number

I'm not sure how to go about this, my program is supposed to get the user to input an IP address. the program is then supposed to return a value in decimal notation. e.g 134.115.64.1 is input and 2255699969 is output.

I was wondering if i could store 134,115,64 and 1 in variable. if so, how could i go about it? A link to any sort of tutorial would be great as i haven't managed to find one my self.

Thanks

Upvotes: 3

Views: 454

Answers (5)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

I am yet not able to understand your question properly.... but will try to do it...

String s = "134.115.64.1";

    String[] arr = s.split("\\.");

    ArrayList<Long> ar = new ArrayList<Long>();

    for(String j : arr){

    ar.add(Long.parseLong(j)); // All the Number are Stored in this ArrayList

     }

    System.out.println(ar);

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533660

A trick for parsing IP addresses

BigInteger ip = new BigInteger(1,InetAddress.getByName("134.115.64.1").getAddress());
// or
long ip = InetAddress.getByName("134.115.64.1").hashCode() & 0xffffffffL;

System.out.println(ip);

prints

2255699969

Upvotes: 2

Adam
Adam

Reputation: 36723

You could use a regex to rewrite into a calculation, then pass that calculation through the JavaScript engine. I wanted to use bitshift operators, but they only work for 32 bit signed numbers.

String input = "134.115.64.1";
String sum = input.replaceAll("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)",
        "($1 * 16777216) + ($2 * 65536) + ($3 * 256) + $4");
System.out.println(sum);
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");

double result = (Double) engine.eval(sum);
System.out.println((long) result);

Upvotes: 0

phatfingers
phatfingers

Reputation: 10250

long longIP(String ip) {
    String[] octets = ip.split("\\.");
    long ipLong = 0;
    for (int i = 0; i < 4; i++) {
        ipLong = ipLong * 256 + Long.parseLong(octets[i]);
    }
    return ipLong;
}

Upvotes: 0

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

You can do something like :

String str = "134.115.64.1";

String arr[] = str.split("\\.");

int[] ips = new int[arr.length];
for(int i=0; i<arr.length;i++)
    ips[i] = Integer.parseInt(arr[i]);

Upvotes: 2

Related Questions