Note: This answer has been heavily edited due to lack of information in original question. This version of the answer is now based on the updated question with enough information. For history, check the edit log.
Two things:
&&
is used between Boolean expressions, to determine the logical AND-value
^
in C# means XOR, not raised-to-the-power-of. You didn't ask a question about this but it was inevitable that you discovered that ^
didn't appear to be doing its job.
The &&
is easily handled, since it can be replaced with a single &
instead, which has a dual meaning, depending on context. Either it is a full-evaluation logical AND operator (&&
is a short-circuited one), or it is a bitwise operator, which is what you want here.
The ^
is different though. The most direct equivalent is Math.Pow, but in this case, a better alternative is available, bit-shift.
The case of 2^X
can be thought of as shift the 1-bit X positions to the left, and shift bits to the left has its own operator, the <<
operator.
So 2^X
can be replaced with 1 << X
.
In this context, here's what you want for your inner-most if-statement:
if ((intNumber & (1 << index)) != 0)
a = a + "1";
else
a = a + "0";
Plug that into a loop like you have in your bottom example, and you get this:
for (Int32 index = 7; index >= 0; index--)
if ((intNumber & (1 << index)) != 0)
bin = bin + "1";
else
bin = bin + "0";
Now, concatenating strings like this generates GC pressure, so you should probably either store these digits into a Char
array, and construct the string afterwards, or use the StringBuilder class. Otherwise you're going to build up 8 (from my example) differently sized strings, and you're only going to use and keep the last one. Depending on circumstances this might not pose a problem, but if you call this code many times, it will add up.
Here's a better version of the final code:
Char[] digits = new Char[8]; // change if you want more/fewer digits
for (Int32 index = 0; index < digits.Length; index++)
if ((intNumber & (1 << index)) != 0)
digits[digits.Length - 1 - index] = '1';
else
digits[digits.Length - 1 - index] = '0';
bin = new String(digits);
However, and here's the kicker. There is already a way to convert an Int32 value to a string full of binary digits in .NET, and it's the Convert.ToString method. The only difference is that it doesn't add any leading zeros, so we have to do that ourselves.
So, here's the final code you should be using:
String bin = Convert.ToString(intNumber, 2).PadLeft(8, '0');
This replaces the whole loop.