DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C# (http://www.daniweb.com/forums/forum61.html)
-   -   Display a number in binary (http://www.daniweb.com/forums/thread156400.html)

ddanbe Nov 10th, 2008 10:52 am
Display a number in binary
 
I thought it was a simple task at first.
Don't ask me why, but I wanted to display a number in it's binary form.
Manipulating bits in C# seems a bit(no pun...) harsh.
The best I could come up with was :
static void Displaybinary( uint i) 
        {
            const byte cByteSize = 8; //like the use of constants that seldom change

            int maxbit = sizeof(uint) * cByteSize - 1;

            uint d = Convert.ToUInt32(Math.Pow(2, maxbit)); //here d=2^31

            for (uint size = d; size > 0; size = size / 2)
            {
                if (Convert.ToBoolean(i & size))  //C# is very picky here
                    Console.Write("1 ");
                else
                    Console.Write("0 ");
            }
            Console.Write("\n");
        }
I tried to make it generic, but that's not that much of a problem,
beside the feeling I'm reenventing the wheel here, I'm not feeling so happy with the code.
Can anyone make any better suggestions?

dickersonka Nov 10th, 2008 11:05 am
Re: Display a number in binary
 
how about

int myValue = 6000;
Debug.WriteLine(Convert.ToString (myValue, 2));

little less lines of code

ddanbe Nov 10th, 2008 11:20 am
Re: Display a number in binary
 
I knew I was somewhere on a wrong path.
The obvious is often just so close, you deny to see it. Thanks for putting me on track!


All times are GMT -4. The time now is 9:55 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC