Terminate the loop when number
reaches 0
. At that point there are no more non-zero bits to pull off:
public static string ConvertIntToBinary(uint value)
{
int totalbits = sizeof(int) * 8;
char[] result = new char[totalbits];
int bits = totalbits;
uint number = value;
while (bits > 0)
{
bits--;
uint remainder = number % 2;
result[bits] = remainder == 0 ? '0' : '1';
number /= 2;
if (number == 0)
break;
}
return new string(result, bits, totalbits - bits);
}
I fixed an error in the code: there are 8 bits in a byte, and not 16 as per your code. I also simplified a few parts of the code. I used a conditional expression which is more concise than the if
. And I introduced another local variable to hold the working value to avoid modifying the actual parameter. This is generally good practise that makes debugging easier. I also used uint
for the input parameter since the entire approach depends on the value being positive.
Note that the termination is inside the loop rather than in the while
test. If you test for number
equal to 0
in the while condition then you will end up returning the empty string for an input of 0
.