dafid
dafid

Reputation: 3

What did i mess up in this for loop?

So what i'm trying to achieve here is basically doing a subnet lookup (in networking).

for (i = 0; i < sorEgy.Length; i++)
{
    if (sorEgy[i] == 1 && sorKetto[i] == 1)
    {
        Console.Write("1");
    }
    else
    {
        Console.Write("0");
    }
}

sorEgy is the given IP in binary: 11000000101010000000000000100000 is for the given IP of 192.168.0.32.

sorKetto is the binary mask:11111111111111111111111100000000 is for /24 which means 24 1-s.

With this for loop, i wanted to write 1 in the output if both strings have a 1 at i, and write a 0 if they don't match. I can't really think of what the problem could be.

Upvotes: 0

Views: 229

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660048

The values being indexed are strings of the form "100101010101111"... The index operator on the string produces a char, and a char may be compared to an int, which you are doing. But the int is the Unicode 16 bit encoding of that character, not the text of that character.

Unicode encoding 1 is an unprintable formatting code for "start of heading", not the character 1. If you want to compare to the character 1 then use '1', not 1, or use the Unicode encoding of the character 1, which is 49. The preferred way to do it would be '1', as comparing against 49 looks strange, to say the least.

Upvotes: 2

Related Questions