11

From what I understand the & operator is similar to the && operator except that the && only checks the second if the first is true, while the & checks both regardless of the result of the first one. Basically the && just saves a little time and power.

If that is so, then how does this code work?

int l = 0;
if ((l & 8) != 0 && (l & 4) == 0){ do something}

what does the (l & 8) and the (l & 4) do? What does the & do in this case?

PakkuDon
  • 1,627
  • 4
  • 22
  • 21
nife552
  • 213
  • 1
  • 2
  • 8

1 Answers1

17

& and && are two different operators but the difference is not what you've described.

& does the bit-wise AND of two integers and produces a third integer whose bit are set to 1 if both corresponding bits in the two source integers are both set to 1; 0 otherwise.

&& applies only to two booleans and returns a third boolean which will be true if both the input booleans are true; false otherwise.

Raffaele Rossi
  • 1,079
  • 5
  • 11
  • That makes a lot more sense. Does it use the binary codes from ASCII, or just straight binary 0 being 0, 1 being 1, 10 being 2, and so on? – nife552 Dec 17 '13 at 23:31
  • To use your terminology it uses "just straight binary 0 being 0, 1 being 1, 10 being 2, and so on", which is known as [binary number](http://en.wikipedia.org/wiki/Binary_number). [ASCII](http://en.wikipedia.org/wiki/ASCII) is a way of coding "written alphabet" characters to a binary numbers (aka character-encoding). There exist others like [EBCDIC](http://en.wikipedia.org/wiki/EBCDIC) or [UNICDE](http://en.wikipedia.org/wiki/UNICODE) – Raffaele Rossi Dec 17 '13 at 23:59