-1

I'm trying to do some Binary AND operations in c# based on MSDN article about & Operator

if i do:

1111 & 10 = 2 (0010) // Which is what i expect

However,

1111 & 100 = 68 (1000100) // Which is **not** what i expect.

I would have thought the output would have been 100

enter image description here

What am i missing?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Cadab
  • 467
  • 9
  • 19

3 Answers3

7

The numbers you specified, 1111 and 100, are being treated as base 10 numbers, not binary numbers.

If you want the binary integer 1111 you should enter 15, as that's the base 10 version. So:

15 & 4 will become 4, as expected.

There is no syntax in C# for specifying an integer literal in binary. You don't have any choice but to convert them into base ten yourself, or use a runtime-conversion such as through Convert.ToInt.

Servy
  • 202,030
  • 26
  • 332
  • 449
3

In addition to using decimal, hexidecimal also works if prefixed with 0x, e.g. 0xF & 0x4

However, while there is no prefix for binary literals, you can do this:

Convert.ToInt32("1111", 2) & Convert.ToInt32("100", 2)

weston
  • 54,145
  • 21
  • 145
  • 203
2

The output is correct.

The point is that you are considering the numbers as binary numbers. Where as the numbers here are treated as decimal integers. There is no binary constants in C# up to 6 as you can see from C# specification - integer literals and SO question C# binary literals.

Find below the explanations however.

1111          10001010111
& 10        & 00000001010
= 2         = 00000000010

 1111         10001010111
& 100       & 00001100100
= 68        = 00001000100

More information on & operator can be found in MSDN.

Community
  • 1
  • 1
Adarsh Kumar
  • 1,134
  • 7
  • 21