C # Why 127 = this bit string?

Given this code, which prints all the bits as a whole:

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 is he typing:

 1000000000000000000000000011111110000000000000000000000000111111 

Firstly, I loop correctly, since I expect the last 7 digits to be 1

Secondly, why is there 1 in the middle? I would expect all of them to be 0, except for the final 7 1.

+4
source share
2 answers

1 << i is a 32-bit integer and thus overflows.
I think 1l << i fix this.
((long)1)<<i may be more readable.

In addition, you have a "one by one" error. You want to go from 63 to 0, not from 64 to 1. Since 1 <1 is 2, not 1.

+18
source

Are you wondering why your code is broken, or are you just trying to display it as binary?

If the latter, then you can just do it and not reinvent the wheel:

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

Or, if you want to print all 64 digits:

 string asBinary = Convert.ToString(intThisHand, 2).PadLeft(64, '0'); 
+7
source

All Articles