2012-10-29 53 views
2

我嘗試下面的代碼顯示數字的二進制等價的,但我得到一個錯誤,我沒有得到錯誤背後的原因:顯示一個十進制數成等效的二進制數

using System; 

class NumToBin{ 
    static void main(){ 
     int num=7; 
     for(int i=0;i<=32;i++){ 
      if(num &(1<<i)==1)// getting an error on this line 
       Console.WriteLine("1"); 
      else 
       Console.WriteLine("0"); 
     } 
     Console.ReadKey(true); 
    } 
} 

我得到了以上代碼的錯誤,我不知道這個錯誤背後的原因?

Operator '&' cannot be applied to operands of type 'int' and 'bool' (CS0019)

+8

您是否嘗試過'Convert.ToString(1,2)'? –

+1

此外,作爲參考(即使這真的不是你的問題是關於):http://stackoverflow.com/questions/923771/quickest-way-to-convert-a-base-10-number-to- any-base-in-net –

+0

@LB:您的評論值得成爲一個全面的答案。任何時候你可以減少90%左右的代碼是一件美麗的事情! –

回答

2

運算符優先級錯誤,請嘗試if ((num & (1<<i)) == 1)

只有 32位在int。將循環謂詞更改爲i < 32,而不是i<=32

或:

for(int i=0; i < 32; i++) 
    Console.WriteLine((num & (1<<i)) == 0 ? "0" : "1"); 

修訂

for(int i=31; 0 <= i; --i) 
    Console.WriteLine(((num >> i) & 1) == 0 ? "0" : "1"); 
+0

隨着你的邏輯我得到1110000000000000000000000000爲7我可以以任何方式扭轉它獲得00000000000000000000000000000111這對二進制數更有意義嗎? – Afaq

+0

@Raptor - 反轉你的for循環。從32計數到0. –

+0

@DaveZych - 非常感謝。我知道了:) – Afaq

相關問題