Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Why does 127 = this bit string?

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.

like image 950
Tom Gullen Avatar asked Nov 28 '22 04:11

Tom Gullen


1 Answers

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.

like image 62
CodesInChaos Avatar answered Dec 20 '22 21:12

CodesInChaos