DEV Community

Discussion on: Explain bitwise operator Like I'm Five

Collapse
 
drbearhands profile image
DrBearhands • Edited

I will assume this particular 5 year old is pretty advanced and know computers use 1's and 0's and that a CPU is what does the computation (to avoid sounding really condescending).

CPU's work on groups of bits rather than individual ones. Those groups are called bytes. Now there are some cases in which we do want to set the values of some specific bit inside a byte, but the CPU just sees a byte, not a collection of bits! So we need operations on bytes that will allow us to control every single bit. Binary operators let us control individual bits or groups of bits smaller than a byte.

Usually people want to use bitwise operators so they need fewer bits/bytes in total and their program becomes faster or requires less memory/storage. But computers have gotten so fast now that the speed increase is often not worth the effort.


End of ELI5

I would note that this explanation is not entirely correct as bitwise operators may work on types larger than one byte, but the idea is the same.

I've seen bitwise operators used for:

  • Database key on a distributed system: some bits in a 64-bit key were used to determine which machine the entry was stored on while others were used to get the exact entry on that machine. This is no longer a good approach as there are mature NoSQL databases out there that do the same but better.
  • Unions of large boolean arrays. Boolean types are often 32-bit, so you have a potential 32 times speedup here (1 boolean or serves as 32 binary or).
  • Legacy code
  • My own C code during a High Performance Computing project (-: