DEV Community

loading...

Discussion on: Bitwise Operations in C/C++

Collapse
oburejin profile image
oburejin

Can you give some examples when we need bitwise shifting? I’m writing JS and can’t figure out why would I need to use shift.

Collapse
abellgithub profile image
Andrew Bell

Well, you use them when you want to know the values of bits. Tons of systems encode information on as few bits as possible to save space. Compression algorithms map character strings and numeric values to packed bit streams. Transmission protocols store flags and sometimes node addresses as some number of bits that aren't byte multiples. It's ubiquitous in embedded systems.

Collapse
noah11012 profile image
Noah11012 Author

If you're writing code in higher level languages like JS or Python then the need for bitwise operations do not present themselves very often. Two examples requiring the use of bitwise operations are in these videos by Danial Shiffman:

youtube.com/watch?v=MlRlgbrAVOs
youtube.com/watch?v=meGcdIoTYgw

Some uses I can think for the shifting operators are:

  1. To create a bitmask
  2. One of the operations to convert the endianness of some multi-bit value
  3. If you shift a value by 2 then it's a shortcut for multiplication or division by two depending on shift operator used.

Daniel Shiffman goes into more detail in this other video of his:

youtube.com/watch?v=oCBlwsY8sR4

Collapse
deciduously profile image
Ben Lovy

They're useful for hash functions, and bitwise XOR can be used instead of integer addition but it's probably not actually any faster.

Collapse
somedood profile image
Basti Ortiz (Some Dood)

Shameless plug here, but I wrote an article not so long ago about the use cases of bitmasking. I used JavaScript for my examples if that helps you to figure out why you would need it. I also highly recommend reading through the comments and discussion of the article. People mentioned a lot of use cases for bitmasking in general there.

Collapse
andzsinszan profile image
Gábor Pintér

For example in audio processing, when manually extracting samples from byte arrays.