看twit.tv節目編碼101(第2集)時,我遇到了這個問題。代碼是預先寫好的,但我們被要求改變它以打印出將整數轉換爲二進制數的while循環的所有值。C#如何刪除0領先的32位從INT
我能夠打印出一個簡單的一切「Console.WriteLine(號);」線。這樣做時,它將返回包含的32位int 0的所有值。
我的問題,是有沒有辦法修剪或去除所有多餘的0在循環的劃分(不是在最後的二進制數),所以他們不打印?下面是該程序的代碼:
public static string ConvertIntToBinary(int number)
{
int bits = (sizeof(int) * 16); //32bits
char[] result = new char[bits]; //Array to hold the binary numbers http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
while (bits > 0)
{
bits = bits - 1;
int remainder = number % 2; //% called mod or modulo which computes the remainder after dividing http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
if (remainder == 1) //If remainder is 1, store it as 1
result[bits] = '1';
else
result[bits] = '0'; //Otherwise store it as 0
number = number/2; //Take the original number, divide it by 2
Console.WriteLine(number);
}
return new string(result).TrimStart('0'); //return the result as a string ,removing extra 0's
}
'C#如何從32位int中刪除前導0' - 'int'沒有任何前導零。這只是一個整數值。 –
@HighCore你看過實際的問題還是隻看標題? – Andy
@只是標題。這就是我一直在做的事情。我懶得想看看他的防守,其餘 –