Navigation



3.8 — Bitwise operators

Bit manipulation operators manipulate individual bits within a variable.

Why bother with bitwise operators?

In the past, memory was extremely expensive, and computers did not have much of it. Consequently, there were incentives to make use of every bit of memory available. Consider the bool data type — even though it only has two possible values (true and false), which can be represented by a single bit, it takes up an entire byte of memory! This is because variables need unique addresses, and memory can only be addressed in bytes. The bool uses 1 bit and the other 7 go to waste.

Using bitwise operators, it is possible to write functions that allow us to compact 8 booleans into a single byte-sized variable, enabling significant memory savings at the expense of more complex code. In the past, this was a good trade-off. Today, it is not.

Now memory is significantly cheaper, and programmers have found that it is often a better idea to code what is easiest to understand and maintain than what is most efficient. Consequently, bitwise operators have somewhat fallen out of favor, except in certain circumstances where maximum optimization is needed (eg. scientific programs that use enormous data sets, or games where bit manipulation tricks can be used for extra speed). Nevertheless, it is good to at least know about their existence.

There are 6 bit manipulation operators:

Operator Symbol Form Operation
left shift << x << y all bits in x shifted left y bits
right shift >> x >> y all bits in x shifted right y bits
bitwise NOT ~ ~x all bits in x flipped
bitwise AND & x & y each bit in x AND each bit in y
bitwise OR | x | y each bit in x OR each bit in y
bitwise XOR ^ x ^ y each bit in x XOR each bit in y

Note: In the following examples, we will largely be working with 4-bit binary values. This is for the sake of convenience and keeping the examples simple. In C++, the number of bits used will be based on the size of the data type (8 bits per byte).

Left shift and right shift operator

The bitwise left shift (<<) shifts operator bits to the left. For example, consider the number 3, which is binary 0011. Left shifting by 1 (3 << 1) changes 0011 to 0110, which is decimal 6. Note how each bit moved 1 place to the left. Left shifting by 2 (3 << 2) changes 0011 to 1100, which is decimal 12. Left shifting by 3 (3 << 3) changes 0011 to 1000. Note that we shifted a bit off the end of the number! Bits that are shifted off the end of the binary number are lost.

The bitwise right shift (>>) operator shifts bits to the right. Right shifting by 1 (3 >> 1) changes 0011 to 0001, or decimal 1. The rightmost bit shifted off the end and was lost!

Although our examples above are shifting literals, you can shift variables as well:

unsigned int nValue = 4;
nValue = nValue << 1; // nValue will be 8

Rule: When dealing with bit operators, use unsigned variables.

Programs today typically do not make much use of the bitwise left and right shift operator in this capacity. Rather, you tend to see the bitwise left shift operator used with cout in a way that doesn’t involve shifting bits at all! If << is a bitwise left shift operator, then how does cout << "Hello, world!"; print to the screen? The answer is that cout has overridden (replaced) the default meaning of the << operator and given it a new meaning. We will talk more about operator overloading in a future section!

Bitwise NOT

The bitwise NOT operator (~) is perhaps the easiest to understand of all the bitwise operators. It simply flips each bit from a 0 to a 1, or vice versa. Note that the result of a bitwise NOT is dependent on what size your data type is! For example, with 4 bits, ~4 (0100 binary) evaluates to 1011, which is 11 in decimal. In an 8 bit data type (such as an unsigned char), ~4 (represented as ~0000 0100) evaluates to 1111 1011, which is 251 in decimal!

Bitwise AND, OR, and XOR

Bitwise AND (&) and bitwise OR (|) work similarly to their logical AND and logical OR counterparts. However, rather than evaluating a single boolean value, they are applied to each bit! For example, consider the expression 5 | 6. In binary, this is represented as 0101 | 0110. To do (any) bitwise operations, it is easiest to line the two operands up like this:

0 1 0 1 // 5
0 1 1 0 // 6

and then apply the operation to each column of bits. If you remember, logical OR evaluates to true (1) if either the left or the right or both operands are true (1). Bitwise OR evaluates to 1 if either bit (or both) is 1. Consequently, 5 | 6 evaluates like this:

0 1 0 1 // 5
0 1 1 0 // 6
-------
0 1 1 1 // 7

Our result is 0111 binary (7 decimal).

We can do the same thing to compound OR expressions, such as 1 | 4 | 6. If any of the bits in a column are 1, the result of that column is 1.

0 0 0 1 // 1
0 1 0 0 // 4
0 1 1 0 // 6
--------
0 1 1 1 // 7

1 | 4 | 6 evaluates to 7.

Bitwise AND works similarly. Logical AND evaluates to true if both the left and right operand evaluate to true. Bitwise AND evaluates to true if both bits in the column are 1) Consider the expression 5 & 6. Lining each of the bits up and applying an AND operation to each column of bits:

0 1 0 1 // 5
0 1 1 0 // 6
--------
0 1 0 0 // 4

Similarly, we can do the same thing to compound AND expressions, such as 1 & 3 & 7. If all of the bits in a column are 1, the result of that column is 1.

0 0 0 1 // 1
0 0 1 1 // 3
0 1 1 1 // 7
--------
0 0 0 1 // 1

The last operator is the bitwise XOR (^), also known as exclusive or. When evaluating two operands, XOR evaluates to true (1) if one and only one of it's operands is true (1). If neither or both are true, it evaluates to 0. Consider the expression 6 ^ 3:

0 1 1 0 // 6
0 0 1 1 // 3
-------
0 1 0 1 // 5

It is also possible to evaluate compound XOR expression column style, such as 1 ^ 3 ^ 7. If there are an even number of 1 bits in a column, the result is 0. If there are an odd number of 1 bits in a column, the result is 1.

0 0 0 1 // 1
0 0 1 1 // 3
0 1 1 1 // 7
--------
0 1 0 1 // 5

Bitwise assignment operators

As with the arithmetic assignment operators, C++ provides bitwise assignment operators in order to facilitate easy modification of variables.

Operator Symbol Form Operation
Left shift assignment <<= x <<= y Shift x left by y bits
Right shift assignment >>= x >>= y Shift x right by y bits
Bitwise OR assignment |= x |= y Assign x | y to x
Bitwise AND assignment &= x &= y Assign x & y to x
Bitwise XOR assignment ^= x ^= y Assign x ^ y to x

For example, instead of writing nValue = nValue << 1;, you can write nValue <<= 1;.

Summary

Summarizing how to evaluate bitwise operations utilizing the column method:

When evaluating bitwise OR, if any bit in a column is 1, the result for that column is 1.
When evaluating bitwise AND, if all bits in a column are 1, the result for that column is 1.
When evaluating bitwise XOR, if there are an odd number of 1 bits in a column, the result for that column is 1.

Quiz

1) What does 0110 >> 2 evaluate to in binary?
2) What does 5 | 6 evaluate to in decimal?
3) What does 5 & 6 evaluate to in decimal?
4) What does 5 ^ 6 evaluate to in decimal?

Quiz answers

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

3.x -- Comprehensive quiz
Index
3.7 -- Converting between binary and decimal

37 comments to 3.8 — Bitwise operators

  • Cody

    you put in the table that AND, OR, and XOR flip all digits in x but they do not.

    [ Aah, the perils of copy and paste. :) Fixed. -Alex ]

  • Cody

    When you do the compound XOR expression the result 0101 would equal 5 not 1.

    [ Fixed. -Alex ]

  • [...] 2007 Prev/Next Posts « 3.6 — Logical operators | Home | 3.8 — Bitwise operators » Sunday, June 17th, 2007 at 11:14 [...]

  • Stuart

    What’s the difference in these: 3 << 1 and 3 <<= 1?

    • From what I understand, the end answer is the same, but in the second case the 3 itself changes to 6 (3 becomes bitwise shifted to the left 1, which is decimal 6). Whereas in the first case 3 stays 3 even after the operation; you’d need an x = 3 << 1 for example for it to have any context.

      • boudiaf

        3 << 1 returns 6 whereas 3 <<= 1 does not compile since “3″ is not a variable name…

        int x = 3; x = x << 1 ; and int x = 3 ; x <<= 1 ; are equivalent; eventually x = 6.

    • x <<= y is the same as x = x << y. Because of this, 3 <<= 1 is the same as 3 = 3 << 1, which obviously makes no sense since you can’t assign a value to the number 3!

  • Argon

    Phun to look at ASCII table and how it is built up regarding bitwise operations.
    I.e. Converting from upper to lower case.

    A=65=01000001
    a=97=01100001
      32=00100000

    So 65^32 (or A^32) gives 97 (or a).
    So 97^32 (or a^32) gives 65 (or A).

    #include <iostream>

    int main()
    {
        using namespace std;
        char chX,chX32;
        for(int i=65;i<91;i++)
        {
            chX = i;
        chX32 = i^32;
        cout << i << ":t" << chX << "tt" << int(chX32) << ":t" << chX32 << "tt";
        chX32 = chX32^32;
        cout << int(chX32) << ":t" << chX32 << endl;
        }
        return 0;
    }

  • [...] how the bit-logic works in order to use the class (though here’s a link to the lesson on bitwise operators if you want to figure it out, but need a refresher on how bitwise operators [...]

  • miroslav

    please,..is it possible to give me a usage (or compare use of bitwise operands and normal byte variables)? I understand the bit operation, but can not fing the ‘added value’ (for example in gaming).

    thanks…

    • anas.s

      to miroslav, jeff & sunilla,

      there’s a lot of use for bitwise operation.

      there might be time when you will have to deal with data represented in binary or some other kind of number base other than decimal or words (as in ASCII)

      example 1,

      you want to write a software that would evaluate poker hands.
      you could encode the hands in binary form.
      every suite has 13 cards, there are 4 suites.
      assign every suite 2 bytes, which give 16 bits, of which we’ll use 13bits.
      each of that bit represent one of the card from A, K, Q, J, 10, 9….. (from bit12 to bit10).
      to represent all 4 suites, there are 8 bytes… (32 bit)

      if you represent each card in ASCII, like 7d for Seven Diamonds, it takes 2 bytes (1 byte for each ASCII character).
      if you want to pass information of 10 cards, it takes you 10 x 2 bytes = 20 bytes.
      where as if you use binary information it still gonna take 8 bytes.

      plus, if you represent it in ASCII, you’d have to do loopings to sort the hands in order from the highest value to the lowest value. if you do it in binary, you dont have to worry about the order, it’s already in order.

      You could also do bitwise operation on your 8-bytes representation of the cards to do comparison, or check if certain card is there or if it’s a flush…. and many more.

      It’s an invaluable tool when you need to work smart instead of work hard.

      another use is when you decide to take up microcontroller as a hobby. Like Arduino for example, where memory is still a precious commodity and speed is important.

      when doing programming you will deal with logic a lot of times…..
      sometime your IF statement is gonna be a very long one that it’s hard to read, all entangled in nested parenthesis.
      encoding them into binary representation can make it a lot easier.

      Maybe if you have electronics background or at least some appreciation in digital logic design, it help you to appreciate bitwise operation more.

      • anas.s

        correction

        you want to write a software that would evaluate poker hands.
        you could encode the hands in binary form.
        every suite has 13 cards, there are 4 suites.
        assign every suite 2 bytes, which give 16 bits, of which we’ll use 13bits.
        each of that bit represent one of the card from A, K, Q, J, 10, 9….. (from bit12 to bit10).
        to represent all 4 suites, there are 8 bytes… (32 bit)

        correction : each of that bit represent one of the card from A, K, Q, J, 10, 9….. (from bit12 to bit0).

  • jeff

    thanks to you alex, i learned the operation of bitwise operators but i dont know where can i use it. can you give me a site of example for program application.

  • sunilla
     i want to write the bits on an output file, that is supposed to be compressed file of an original file using the huffman technique just like if the code for A is 110, then i want to write these 3-bits on output file. how can i manage it.from the above mentioned explanations i got an idea about bit manipulation but i still dont get the complete idea of resolving my issue.
  • CompNerd

    I’m looking to create a new PRNG, and I need to be able to assign individual bits within a byte… Is there a way to decide what each bit will be within a byte without changing the other bits, and without finding out what symbol (letter/number/other) uses the specific binary code I need and then assigning it?

  • JTO

    Hey Alex, This site is great. Do you know any site that with give an example to try this stuff out.
    Thanks alot.

  • DB

    An easy example is in things like compression.. you can easily add 0′s and 1′s to things like characters.

    An easy use to display the <> operators:

    You have a character. Display its binary. Using bitwise <>, it is quite easy to.

    char decode = (somesortofcharactefgettingthinghere);
    char tempChar;
    for (int i = 0; i < 8; i++) // we are using a character. It is 1 byte, or 8 bits (or is on my computer).
    {
    tempChar = decode
    tempChar << i;
    tempChar >> 7; // because bits are lost, we can seperate 0′s and 1′s by themselves.
    cout << char;
    }

    I can’t easily explain that, but if you think it out in your head…

    lets say our character is the number 97 (I think thats A, but it does not matter. It is only outputted as A, internally it is a number)

    0 1 1 0 0 0 0 1

    Alright, in our loop, we start by shifting it 0 units to the left. we then shift it to the right 7.

    Our result? 0. Next time, move it 1 unit to the left, 7 to the right. 1. So on and so forth. You could have alternatively used a calculation, but this was just an example.

    • DB

      How about a simple encryption program? Have a secret list of passwords in a text file? Render it useless to hackers with a simple changing of 0′s to 1′s, and 1′s to 0′s! (this both encrypts and unencrypts it):

      #include fstream
      #include iostream

      using namespace std;

      int main()
      {
      char choice[250];
      fstream file;
      cout <> choice; //EDIT: this is wtf scrweed up by the site.. youi know how to use cin I assume >.>

      file.open(choice, ios::binary | ios::in);
      if (!file.is_open())
      return 0;
      char *data;
      long begin, end, size;
      file.seekg(0, ios::beg);
      begin = file.tellg();
      file.seekg(0, ios::end);
      end = file.tellg();
      size = end – begin;
      data = new char[size];
      file.seekg(0, ios::beg);
      file.read(data, size);
      file.close();
      for (long i = 0; i < size; i++)
      data[i] = ~data[i];
      file.open(“output.woo”, ios::out | ios::binary);
      file.seekp(0, ios::beg);
      file.write(data, size);

      return 0;
      }

  • Zak

    So if you did (7 >> 2), you get from 0111 to 0001, which is the number 1. Now how can you get back from that to 7? So the main use for this is so noone understands it except for the person who changed the value? To me, these bitwise operators seem useless except for Bitwise Not (~). I really do not understand what good you can get out of doing 5|6.

  • i had read a c++ book..i dint have this kind of satisfaction after reading the book.. its truly amazing..thank you guru alex.. god bless you..

  • Mkc

    I’ve really enjoyed the tutorial so far, mainly because of the real life examples we’ve been given along the way.

    The brief elucidation at the top of this page is great but could you go a bit further and tell us why it’s useful to be able to turn an 8bit 4 into a 251?! What’s the practical use of these operators?

    Thanks in advance and thanks for an already brilliant tutorial.

    M

    • posentel

      I am a college instructor, and have taught Discrete Mathematics using C++, and have also taught video game programming using C++. I’m going through the learncpp website to pick up teaching hints and language details I may have missed. This is the first section that I felt was poorly explained. He should not have been explaining bitwise operators in terms of their integer representations, in general, such as changing a 4 into a 251. That isn’t how they are used.

      Back in the dinosaur days of computers, memory was precious, and most real programming was done in assembly language. Many home computers only had 16K of RAM, and multiplication wasn’t built into the processor. If you wanted to do multiplication quickly (the computers weren’t that fast), you often wanted a precomputed multiplication table. But if you needed it for 1-100, that was 10000 entries, most of the 16K. Here’s what we did: x*y = ((x+y)^2-(x-y)^2))/4. Addition and subtraction were built into the processor, and now we only need a table of squares up to 200, so 200 entries, not 10000! And division by 4? Super easy, just do a right shift of 2, so >>2. Just like in decimal dividing by 100 corresponds to moving the decimal 2 places, dividing by 4 corresponds to moving the “decimal point” 2 places in binary, and dropping the remainder. So left and right shifts correspond to multiplying and dividing by powers of two. With optimized compilers, this isn’t as useful as it used to be.

      Bitwise & and | are still used often for masks, especially graphically. For example, suppose we want a flashlight effect on the screen, and only the 4 middle bits of 8 bits should be lit. The mask 0011 1100 will turn off the bits on each side, and leave the middle 4 alone, with bitwise and:

      1101 1101
      &0011 1100
      ———-
      0001 1100

      And notice what the same mask does with bitwise or:

      1101 1101
      |0011 1100
      ———-
      1111 1101

      It turns the 4 middle bits on, and leaves the outer 4 alone.

      What if we wanted to turn the high bit of a byte on, and leave the remaining bits alone, well then we do bitwise or with 1000 0000:

      0101 1100
      |1000 0000
      ———-
      1101 1100

      This is one of the main uses of the bitwise operators. Think how much they were used with the original black and white Mac Classic graphically. Bitwise and would dim sections of the screen, and then bitwise or could be used to draw something else in place. And bitwise or could also be used to draw a pattern on top of an existing picture in paint programs.

  • joe

    Is there a logical XOR operator.

  • MattFraust10

    Hey joe,

    If you look back on section 3.6, the 8th comment from the top of the comments is one posted by Florian in response to the 7th comment, made by RonnieTheBear.
    The post begins as stated below:

    Comment by Florian
    2009-12-04 13:36:39
    Hey Ronnie,

    This should answer your question. There is no logical XOR in C++, but Florian gives an alternate option one could use to achieve the same ends.

  • [...] 3.8 — Bitwise operators C++ Programming |  Print This Post « 16.4 — STL algorithms overview    [...]

  • panchopaz

    Hi, excellent tutorial.

    I’m an electronics student and I use C to program embedded systems. Now I’m looking to switch from C to C++.

    In embedded systems it is really useful to have the bitwise operators. For example, bitwise operator target cpu registers and variables that control several peripheral of the cpu without altering other bits.

    Also it is usefull when output pins are shared for several function in the same IO bank.

    Perhaps in computers they are disappearing, but embedded systems still use them!

    Save the |= and &= !!

  • jwburks1976

    I had been studying for hours a day, and was fine until I got to this point. For some reason, my brain isn’t grasping it. I remember running into the same problem with pointers years ago, but I finally got what they are. I must be stupid.

  • ghnat2013

    int flags = 0xB2;
    int mask;
    What of the following are the correct statements if bit 6 of flags is to be toggled?
    Answer mask=0xBF;
    flags = flags ^ mask;
    mask=0×40;
    flags = flags ^ mask;
    mask=0xBF;
    flags = flags | mask;
    mask=0×40;
    flags = flags | mask;

  • ghnat2013

    Assuming flags = 0xAA, what is the value of flags after the following statement is executed?
    cout << (flags << 2);
    Answer 0xA8
    0×54
    0xAA
    AA2

  • ghnat2013

    Which of the following is a bitwise operator?
    Answer *
    &&
    &
    %

  • ghnat2013

    To turn bit 3 of a variable to 0. the correct way is to:
    Answer set the mask to 0xEF and peform the bitwise AND operation with the variable.
    set the mask to 0xF7 and peform the bitwise AND operation with the variable.
    set the mask to 0xEF and peform the bitwise OR operation with the variable.
    set the mask to 0xF7 and peform the bitwise OR operation with the variable.

  • ghnat2013

    Which of the following statements will display “Problem!” if bit 2 of flags is a ’0′?
    Answer if ((flags & 0×04) == 0×04) cout << "Problem!";
    if ((flags & 0×04) != 0×04) cout << "Problem!";
    if ((flags ^ 0×04) == 0×04) cout << "Problem!";
    if ((flags ^ 0×04) != 0×04) cout << "Problem!";

    2 points

  • ghnat2013

    pls reply to the questions

  • mandeep

    could anyone sove this program for meplzzzzzzzz

    Bitwise example, run it and print out the results, reprogram it using OOP (c++)
    concepts

    #include
    main ()
    {
    unsigned char x = ’11′;
    unsigned char y = ’27′;
    cout << "x = " << oct << short(x) << '\n';
    cout << "y = " << oct << short(y) << '\n';
    cout << "~x = " << oct << (short)(~x) << '\n';
    cout << "x & y = " << oct << (short)(x & y) << '\n';
    cout << "x | y = " << oct << (short)(x | y) << '\n';
    cout << "x ^ y = " << oct << (short)(x ^ y) << '\n';
    cout << "x << 2 = " << oct << (short)(x << 2) << '\n';
    cout <> 2 = ” << oct <> 2) << '\n';

You must be logged in to post a comment.