Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Noah11012
Noah11012

Posted on

     

Bitwise Operations in C/C++

Maybe you've stumbled across a perplexing and scary looking line of code:

((value<<2)&32)

You don't know what this is and after some time scouring the internet for answers you come across what is known as bitwise operations. In this post, we'll go over all the bitwise operations possible in C and C++.

Bitwise operations are operations that operate on bit(s). If a bit is 1 then it is said to be "true" or "on". If it is a 0, then it is "false" or "off". Just like arithmetic operators, bitwise operators give a result when the computation is done.

AND

For one bit values, the AND operator gives the result of "on" if both bits are in the "on" state. Otherwise, it produces the value of "off".

1&1==11&0==00&1==00&0==0

For bytes, it goes over each bit and applies the AND operation individually.

10000000&01111111==0000000011000000&11100011==1100000010100110&10000111==1000011010101010&11011011==10001010

OR

Denoted by| in C and C++, this operation produces the state of "on" if any of the bit is in the "on" state.

1|1==11|0==10|1==10|0==0

Just like with the AND operator, the same thing is done with multi-bit values.

XOR

Denoted by^ it is short for exclusive OR. This produces the "on" state if only ONE of the bits is true.

1^1==01^0==10^1==10^0==0

Operations applied to multi-bit values like bytes are done at the bit level just like with AND and OR.

NEG

Negates the state of a bit. The symbol~ is used to denote this operation.

~1==0~0==1

Same with multi-bit values.

Bitmasks

This isn't an operation but something programmers use sometimes when dealing with bitwise operations. You can think of a bitmask as a filter to extract bits from a multi-bit value.

Say we have the byte10100111 and we want to get the first two bits. We can use a bitmask to accomplish this goal. A bit of 0 in bitmask means to ignore and 1 means to extract. In our case, the bitmask would like this:000000011. To apply the bitmask, we use the AND operator.

10100111&00000011==00000011

Shift operators

You've seen these before with<< and>>. They mean "shift to the left" and "shift to the right", respectively.

The operand on the left side is the value being shifted while the operand on the right side is the shift amount.

Unlike the other operators we have looked at, these only work on multi-bit values like bytes.

For demonstration purposes, we will have the value11001011 to play around with.

These operators shift each bit to the direction specified by the type of shifting operator used by a certain amount. Bits that are shifted out of the byte completely are discarded and padded with a zero on the opposite side.

11001011<<1==1001011011001011>>2==00110010

This was a quick article I decided to do after my main Using SDL2 post was released.

Edit:

Thanks to @ccmg for the corrections.

Top comments(7)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
oburejin profile image
oburejin
I am a webdev.
  • Location
    Israel, Raanana
  • Joined

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.

CollapseExpand
 
noah11012 profile image
Noah11012
  • Joined

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

CollapseExpand
 
abellgithub profile image
Andrew Bell
  • Joined

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.

CollapseExpand
 
somedood profile image
Basti Ortiz
Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.
  • Location
    Philippines
  • Education
    B.Sc. Computer Science @ University of the Philippines Diliman
  • Pronouns
    he/him
  • Work
    Full-stack Engineer @ Verdn (YC W22)
  • Joined

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 alsohighly recommend reading through the comments and discussion of the article. People mentioned a lot of use cases for bitmasking in general there.

CollapseExpand
 
deciduously profile image
Ben Lovy
Just this guy, you know?
  • Email
  • Location
    Boston, MA, USA
  • Education
    Currently enrolled @ Champlain College Online
  • Work
    Rust Developer @ Tangram.dev
  • Joined

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

CollapseExpand
 
andzsinszan profile image
Gábor Pintér
speech scientist
  • Location
    Dresden
  • Work
    Senior Research Developer
  • Joined

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

CollapseExpand
 
emcain profile image
Emily Cain
web developer + security engineer. Python, SQL, JavaScript, Go
  • Joined

this article goes into more detail on how bitwise AND, OR, and XOR work in multi-bit values (specifically half-bytes)dev.to/emcain/bitwise-operations-o...

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromNoah11012

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp