Bitwise operations

The operators

Operator Name
| OR
& AND
^ XOR
<< Left shift
>> Right shift
~ Not / One's complement

The OR operator: |

  • Combines two integers together
  • For each bit processed if the bit of any of the members is 1, the result will be 1
  • Used to "activate" bits

The OR operator: |

a: 1 1 0 0
b: 1 0 1 0
a|b 1 1 1 0

The AND operator: &

  • Filter active bits
  • For each bit processed if the bits of both members is 1, the result will be 1
  • Used for masks

The AND operator: &

a: 1 1 0 0
b: 1 0 1 0
a&b 1 0 0 0

The XOR operator: ^

  • Toggle bits
  • For each bit processed if the bits of both members is the same, the result will be 0, otherwise 1

The XOR operator: ^

a: 1 1 0 0
b: 1 0 1 0
a^b 0 1 1 0

The left shift: <<

  • Shifts all bits to the left
  • Discards the overflowing bits
  • Sets to 0 the right most bits
  • AKA: Multiplies by 2

The left shift: <<

a: 0 0 1 1 0 1 = 13
a << 1 0 1 1 0 1 0 = 26
a << 2 1 1 0 1 0 0 = 52

The right shift: >>

  • Shifts all bits to the right
  • Discards the underflowing bits
  • Sets to 0 the left most bits
  • AKA: Divides by 2

The right shift: >>

a: 1 1 0 1 0 0 = 52
a >> 1 0 1 1 0 1 0 = 26
a >> 2 0 0 1 1 0 1 = 13

And my personal favourite....

The not: ~

  • Applied to a single value
  • Toggles all the member's bits
  • Used to create mask

Or complement to one

The not: ~

With signed integers:

~a = -1 * a - 1

~-1 = 0

Or complement to one

if (array.indexOf(val) == -1) // if NOT found

 

vs

 

if (!~array.indexOf(val)) // if NOT found

Real life usages

Real life usages

Group errors in a single value

Create an error reporting

Real life usages

Networking

Encryption

Real life usages

Color storage

RGB color:

  • Red: 0 to 255, 1byte
  • Green: 0 to 255, 1byte
  • Blue: 0 to 255, 1byte
  • Alpha: 0 to 255, 1byte

Real life usages

Color storage

Can be stored in a long (4 bytes)

#B2A3C5CC

R: B2 (178), G: A3 (163), B: C5 (197), A: CC (204)

10110010

10100011

11000101

11001100

which is -1297889844

Real life usages

Color storage

Components retrieval

Red value = (color >> 24) & 255

Green value = (color >> 16) & 255

Blue value = (color >> 8) & 255

Alpha value = color & 255

Real life usages

Flags storage

Collection of boolean values

Can be replaced with a single int to store up to 32 flags

Each boolean take 1 byte in memory

Operations to know

Activate a bit

Deactivate a bit

Get a bit value

Activate a bit

value | (1 << bitIndex)

Deactivate a bit

value & ~(1 << bitIndex)

Get a bit value

value & (1 << bitIndex)

Bitwise Operations

By Ghislain Rodrigues

Bitwise Operations

  • 837