I have this code....

char ch;

            for (int i = 0; i < 10; i++)
            {
                ch = (char)('a' + i);//here
                Console.WriteLine(ch);

                ch = (char)((int)ch & 65503);//and here

                Console.WriteLine(ch + "");
                Console.ReadLine();
            }

Now what I would like to ask is where ('a' + i) is, how is this statement working.

Along with this, the statement ch = (char)((int)ch & 65503). I don't understand this bit...I know 65503 is the decimal value of 1111 1111 1101 1111. I know that ANDing ch and 65503 will change the sixth bit to 0 and then make ch an uppercase A instead of lowercase.

But just cannot understand how it is changing this bit to 0...

Hope this makes sense and someone can help!

Thanks
James

Ok, the first problem ('a' + i). The compiler sees that i is an Int32 so it casts the character 'a' into an Int32 and does the add. The (char) outside the math converts it back into a character.

Second problem. The logic truth table for AND is

Bit 1     Bit 2     Result
  0         0          0
  1         0          0
  0         1          0
  1         1          1

So when you do a bitwise AND (&) it compares corresponding bits using the truth table above and gives back the results. By ANDing the one bit with zero you ensure that the resulting bit will be zero.

Thanks Momerath....I get that now you have explained it...just one last bit...


This statement...in my book...says

if(status & 8)
{
 //bit 4 is on...
}

So 8 is the value of the 4th bit...but how does this statement work...? Does this statement tell the compiler to look at the 4th bit in status and execute if it is set?

hmmmm

First, your book isn't a C# book as that isn't valid C# code (but is valid C/C++ code).

Second, each bit represents a power of 2 and are counted from right to left. Depending if you start counting at 0 or 1 determines which bit :)
So the first bit is 2^0 = 1
2nd bit 2^1 = 2
3rd bit 2^2 = 4
4th bit 2^3 = 8

So if we convert 8 to binary we get 0b00001000

In C/C++ any result in an if statement that is not zero means that it is true, so if we AND status with 8 that would result in 8 if the 4th bit of status is on, which means it would be true.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.