0

When I run this code -

string binNumber="11111000001";
for(int ind=0; ind<binNumber.Length; ind++){
   Console.WriteLine(binNumber[ind]&'1');
}

it prints sequence of 49 and 48 instead of 1 and 0.

I could not understand why is it happening? If I use the XOR operator it prints 1s & 0s. I have seen this behavior for & and | operator. The code can be accessed in the IdeOne here - https://ideone.com/fqZFUY.

Siva Senthil
  • 610
  • 6
  • 22
  • http://www.codeproject.com/Articles/544990/Understand-how-bitwise-operators-work-Csharp-and-V – Soner Gönül Jun 11 '15 at 08:37
  • You shouldn't use `string` to hold binary number. Any *integer type* by nature is better to hold binary. Use e.g. [`UInt16`](https://msdn.microsoft.com/en-us/library/system.uint16(v=vs.110).aspx) to hold value. Only [convert it](http://stackoverflow.com/q/1838963/1997232) to `string` when you want to show it. This way your *binary* arithmetic will work as intended (assuming you will do it with *integer* values and not `string`/`char`). – Sinatr Jun 11 '15 at 08:42
  • 1
    See [BitArray](http://stackoverflow.com/a/20650932/1997232) as well. – Sinatr Jun 11 '15 at 08:49
  • @Sinatr, thanks a ton. I was not aware of this class in the Collections namespace. Plus, is probably the right way to handle the situations I am encountering today. – Siva Senthil Jun 11 '15 at 08:59

2 Answers2

1

'0' has a code of 48 in decimal, or 110000 in binary.

'1' has a code of 49 in decimal, or 110001 in binary.

110000 & 110001 == 110000 == 48 decimal

110001 & 110001 == 110001 == 49 decimal

So when you do Console.WriteLine(binNumber[ind]&'1'); you get 48 or 49 depending on whether binNumber[ind] is '0' or '1'.

Remember that if you do someChar & someOtherChar the compiler does a bitwise AND of the numeric values of those chars.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

The type of an & operation between two char is int. You can see it if you try:

var res = '0' & '0';

and you look at the type of res. (technically this is called "binary numeric promotion", and what happens in this case is that both char are converted to int, then the & is done between two int, and clearly the result is an int. If you are interested it is explained here)

So being the result an int, Console.WriteLine formats it as an int.

Try

Console.WriteLine((char)(binNumber[ind]&'1'));
xanatos
  • 109,618
  • 12
  • 197
  • 280