2

I tried the following code for displaying a number's binary equivalent but i am getting an error and i am not getting the reason behind the error:

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);
    }
}

I got the following error for the above code and i dont know the reason behind this error?

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

Afaq
  • 1,146
  • 1
  • 13
  • 25
  • 8
    Have you tried `Convert.ToString(i, 2)` ? – L.B Oct 29 '12 at 17:41
  • 1
    Also, for reference (even though this really isn't what your question is about): http://stackoverflow.com/questions/923771/quickest-way-to-convert-a-base-10-number-to-any-base-in-net – jeffrey_t_b Oct 29 '12 at 17:41
  • @L.B: Your comment deserves to be a full-fledged answer. Anytime you can reduce code by 90% or so is a beautiful thing! – Michael Sorens Oct 30 '12 at 15:17

2 Answers2

5

Error is a result of operator order of precedence, to fix it you simply need to add parentheses, change:

if(num &(1<<i)==1)

to

if((num & (1<<i)) == 1)
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
2

Operator precedence error, try if ((num & (1<<i)) == 1)

There are only 32 bits in an int. Change for loop predicate to i < 32, instead of i<=32.

or:

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

UPDATED

for(int i=31; 0 <= i; --i)
    Console.WriteLine(((num >> i) & 1) == 0 ? "0" : "1");
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73