Select Page

The AND operation compares each bit in two integers; if both bits are set to “1”, then the final result will be “1”, otherwise it will be “0”. This is done “per-bit”, or “bitwise”.

#### Truth Table:

 AND 1 0 1 1 0 0 0 0

#### Usage:

```// A bitfield whose [[binary]] representation is: 00000000000000000000000000001010
integer a = 10;

// Another bitfield whose binary representation is: 00000000000000000000000000011001
integer b = 25;

// The next line translates to "store the result of AND'ing a and b together" in the variable a_AND_b.
// Its binary representation is 00000000000000000000000000001000, or 8.
integer a_AND_b = a & b;```

The reason a_AND_b is 8, is that the & operator compared the two bitfields passed to it, a and b, and turned on only the bits that were both 1. The operation is written out like this:

```a      00000000000000000000000000001010 // As decimal = 10
b      00000000000000000000000000011001 // As decimal = 25
-----------------------------------------------------------------
a & b  00000000000000000000000000001000 // As decimal = 8```

& is commonly used with the control event, when finding out which buttons were pressed by the user.
For example, if the user is holding down the up arrow:

```control(key controller, integer levels, integer edges) {
// If user is holding down up arrow:
if ((levels & CONTROL_FWD) == CONTROL_FWD) {

// Do stuff...
}
}```

Commonly, many buttons are held down at the same time. Using bitfields then makes sense because each button can be represented by a bit in the levels bitfield.

```control(key controller, integer levels, integer edges) {
// If user is holding down up arrow:
if ((levels & CONTROL_FWD) == CONTROL_FWD) {
// The above translates to: "If the CONTROL_FWD bit is 1 in the levels bitfield"
}

// If user is holding down down arrow:
if ((levels & CONTROL_BACK) == CONTROL_BACK) {
// The above translates to: "If the CONTROL_BACK bit is 1 in the levels bitfield"
}
}```

Here’s the operation (levels & CONTROL_BACK), when the user is holding down both the up and down arrows, written out longwise:

```levels                00000000000000000000000000000011 // As decimal = 3
CONTROL_BACK          00000000000000000000000000000010 // As decimal = 2
-------------------------------------------------------------------------------
levels & CONTROL_BACK 00000000000000000000000000000010 // As decimal = 2```

Credit to: Lslwiki.net (not working) with changes made for brevity and clarity.