views:

151

answers:

2

Given this code which prints all the bits in an integer out:

private string getBitLiteral(bool bitVal)
{
    if (bitVal)
    {
        return ("1");
    }
    else
    {
        return ("0");
    }
}

 

    Int64 intThisHand = 127;

    for (int i = 64; i > 0; i--)
    {
        HttpContext.Current.Response.Write(
            getBitLiteral((intThisHand & (1 << i)) != 0)
        );
    }

Why does it print out:

1000000000000000000000000011111110000000000000000000000000111111

Firstly am I looper correctly as I expect the last 7 digits to be 1's

Secondly, why are there some 1's in the middle? I would expect them all to be 0 except the trailing 7 1's.

+16  A: 

1 << i is a 32 bit integer an thus overflows.
I think 1l << i would fix it.
((long)1)<<i might be more readable.

Additionally you have an off-by-one error. You want to go for 63 to 0 not from 64 to 1. Since 1<<1 is 2 and not 1.

CodeInChaos
Ah, how would I modify this so that it will work correctly on 64 bit integers? It's pretty crucial for my project to handle 64 bit integers.
Tom Gullen
I think either adding the l suffix or casting it to long would fix that.
CodeInChaos
Michael Madsen
Super, that was easy! My loop should be **for (int i = 63; i >= 0; i--)** to fix the leading bit right?
Tom Gullen
Yuliy
+5  A: 

Are you curious about why your code is broken, or are you just trying to display the number as binary?

If the latter then you can just do this rather than re-inventing the wheel:

string asBinary = Convert.ToString(intThisHand, 2);

Or, if you want to pad out all 64 digits:

string asBinary = Convert.ToString(intThisHand, 2).PadLeft(64, '0');
LukeH
Good solution thank you!
Tom Gullen