سؤال

I wrote a program that compares two Strings with bits, e.g.

IP Adress Oct1 => 11000000

Subnetmask Oc1 => 01000000

But the comparison of the 4th octets does not work properly. http://pastie.org/private/xfccedpcrcksa5so6rykmg

The function is called compareBits():

public static String compareBits(String oct, String oct2) {
    String comparison = "";
    for(int i=0; i<=oct.length()-1; i++) {
        if(oct.charAt(i) == oct2.charAt(i) && oct.charAt(i) != 0) {
            comparison = comparison+"1";
        } else {
            comparison = comparison+"0";
        }
    }

    return comparison;
}

On the 4th octet it's displaying the results inversed. (00000001, but should be 10000000)

Can you help me find out where the problem of attached code I have written so far is?

هل كانت مفيدة؟

المحلول

Here's my thought of how your method compareBits should look like:

public static String compareBits(String oct, String oct2) {
    String comparison = "";
    for(int i=0; i<=oct.length()-1; i++) {
        if(oct.charAt(i) == oct2.charAt(i) && oct.charAt(i) != '0') {
            comparison = comparison+"1";
        } else {
            comparison = comparison+"0";
        }
    }

    return comparison;
}

Since you are checking the charAt(), you get a character, but you compare with 0, and not with the char literal '0'. That should do the trick.

On the other hand, I think this task could be archieved with less code, for instance:

long ipL = IpConverter.ipToLong(ip);
long maskL = IpConverter.ipToLong(mask);
System.out.println(IpConverter.longToIp(ipL & maskL));

Regards

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top