# Bitwise Notes

## Bitfield Notes

``````/**
* @param \$flag	Position in the bitfield
* @return Boolean state.
*/
getFlag(\$flag)
return ((\$field & \$flag) == \$flag)
```
```/**
* @param \$flag	Position in the bitfield
* @param \$state	TRUE or FALSE state of the flag.
* @return void
*/
setFlag(\$flag, \$state)
\$field = (\$state ? (\$field | \$flag) : (\$field & ~\$flag));
```
```Bitwise AND	&
0 & 0 == 0
1 & 1 == 1
1 & 0 == 0
```
```Bitwise OR	|		Used to add multiple flags together.
0 | 0 == 0
1 | 1 == 1
1 | 0 == 0
```
```Bitwise XOR	^	"exclusive or"
0 ^ 0 == 0
1 ^ 1 == 0
1 ^ 0 == 1
```
```Bitwise NOT	~		Inverts all bits
~0 == 1
~1 == 0
```
```Bitwise AND NOT		Used to clear flags.
1111 & ~1		== 1110
1111 & ~2		== 1101
1111 & ~4		== 1011
1111 & ~(2 | 4)	== 1001
```
```Bitwise <<			Multiplies by power of 2. Can produce positive or negative integers.
0001 << 1 == 0010
```
```Bitwise >>			Divides by the power of 2. Can produce positive or negative integers.
0010 >> 1 == 0001
```
```Bitwise <<<			Multiplies by power of 2. Produce positive integers only.
```
```Bitwise >>>			Divides by the power of 2. Produce positive integers only.
```
```In binary system: 0 1 0 0 0 1 0 0
The n-th number:  7 6 5 4 3 2 1 0
01000100 = 2^0*0+ 2^1*0 + 2^2*1 + 2^3*0 + 2^4*0 + 2^5*0 + 2^6*1 +2^7*0 = 4 + 64 = 67.
```
```2^n*b
```
```b = 0 or 1
```
```Raise to 2nd Power = 1 << 4
```
```unsigned char a = 1, b = 3, c = 0;
// a = 00000001
// b = 00000011
// c = 00000000
c = a & b ; // -> 00000001 (Position 0 for a & b are both "true")
c = a | b ; // -> 00000011 (Position 0 and 1 for a | b are "true")
c = a ^ b ; // -> 00000010 (Position 0 for a & b are both "false")
```
```Masking Techniques
Finding if the n-th bit is 1 or 0
if(x & (1UL << p))
{
// here it's going to continue if the bit is 1 // true
}
else
{
// here it's going to enter if the bit is 0 // false
}
```
```Printing the n-th bit
printf("%d" !!(x & (1UL << p)));
```
```Set p-th bit to 0
x &= ~ (1UL << p);
```
```Set p-th bit to 1
x |= 1UL << p;
```
```Negate the p-th bit
x ^= 1UL << p;
``````