Search

Meta

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, at least for application programming, it is probably 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, games where bit manipulation tricks can be used for extra speed, or embedded programming, where memory is still limited). 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

Bit manipulation is one of the few cases where you should unambiguously use unsigned integer data types. This is because C++ does not guarantee how signed integers are stored, nor how some bitwise operators apply to signed variables.

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).

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

Bitwise left shift (<<) and bitwise right shift (>>) operators

The bitwise left shift (<<) operator shifts bits to the left. The left operand is the expression to shift, and the right operator is an integer number of bits to shift by. So when we say 3 << 1, we are saying “shift the bits in the literal 3 left by 1 place”.

For example, consider the number 3, which is binary 0011:

3 = 0011
3 << 1 = 0110 = 6
3 << 2 = 1100 = 12
3 << 3 = 1000 = 8

Note that in the third case, we shifted a bit off the end of the number! Bits that are shifted off the end of the binary number are lost forever.

The bitwise right shift (>>) operator shifts bits to the right.

12 = 1100
12 >> 1 = 0110 = 6
12 >> 2 = 0011 = 3
12 >> 3 = 0001 = 1

Note that in the third case we shifted a bit off the right end of the number, so it is lost.

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

Note that the results of applying the bitwise shift operators to a signed integer are compiler dependent.

What!? Aren’t operator<< and operator>> used for input and output?

They sure are.

Programs today typically do not make much use of the bitwise left and right shift operators to shift bits. Rather, you tend to see the bitwise left shift operator used with cout to output text. Consider the following program:

This program prints:

8

In the above program, how does operator<< know to shift bits in one case and output x in another case? The answer is that std::cout has overridden (replaced) the default behavior of the << operator and given it a new meaning (to output text to the console). When the compiler sees that the left operand of operator<< is std::cout, it knows that it should call the version of operator<< that std::cout overrode to do output. If the left operand is an integer type, then operator<< knows it should do its usual bit-shifting behavior.

We will talk more about operator overloading in a future section, including discussion of how to override operators for your own purposes.

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!

Assuming 4 bits:
4 = 0100
~4 = 1011 = 11

Assuming 8 bits:
4 = 0000 0100
~4 = 1111 1011 = 251

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 x = x << 1;, you can write x <<= 1;.

Bit flags

As noted above, using a whole byte to store a boolean leaves 7 of the 8 bits unused. While this generally is fine, in storage-intensive cases where we have lots of related boolean options, it can be useful to "pack" 8 individual booleans into a single byte for storage efficiency purposes. These individual bits are called flags. Since the bits can't be accessed directly, we have to use the bitwise operators to set, unset, or query them.

For example:

To turn a bit on, we use bitwise OR:

To turn a bit off, we use bitwise AND with an inverse bit pattern:

To toggle a bit state, we use bitwise XOR:

To query a bit state, we use bitwise AND:

As a real-life example, in OpenGL (a 3d graphics library), some functions take one or more bit flags as a parameter:

GL_COLOR_BUFFER_BIT and GL_DEPTH_BUFFER_BIT are defined as follows (in gl2.h):

Why are bit flags useful?

Astute readers will note that the above myflags example actually doesn't save any memory. 8 booleans would normally take 8 bytes. But the above example uses 9 bytes (8 bytes to define the options, and 1 bytes for the bit flag)! So why would you actually want to use bit flags?

Bit flags are typically used in two cases:

1) When you have many sets of identical bitflags.

Instead of a single myflags variable, consider the case where you have two myflags variables: myflags1 and myflags2, each of which can store 8 options. If you defined these as two separate sets of booleans, you'd need 16 booleans, and thus 16 bytes. However, using bit flags, the memory cost is only 10 (8 bytes to define the options, and 1 byte for each myflags variable). With 100 myflag variables, your memory cost would be 108 bytes instead of 800. The more identical variables you need, the more substantial your memory savings.

Let's take a look at a more concrete example. Imagine you're creating game where there are monsters for the player to fight. When a monster is created, it may be resistant to certain types of attacks (chosen at random). The different type of attacks in the game are: poison, lightning, fire, cold, theft, acid, paralysis, and blindness.

In order to track which types of attacks the monster is resistant to, we can use one boolean value per resistance (per monster). That's 8 booleans per monster.

With 100 monsters, that would take 800 boolean variables, using 800 bytes of memory.

However, using bit flags:

Using bit flags, we only need one byte to store the resistances for a single monster, plus a one-time setup fee of 8 bytes for the options.

With 100 monsters, that would take 108 bytes total, or approximately 8 times less memory.

For most programs, the amount of memory using bit flags saved is not worth the added complexity. But in programs where there are tens of thousands or even millions of similar objects, using bit flags can reduce memory use substantially. It's a useful optimization to have in your toolkit if you need it.

2) Imagine you had a function that could take any combination of 32 different options. One way to write that function would be to use 32 individual boolean parameters:

Hopefully you'd give your parameters more descriptive names, but the point here is to show you how obnoxiously long the parameter list is.

Then when you wanted to call the function with options 10 and 32 set to true, you'd have to do so like this:

This is really difficult to read (is that option 9, 10, or 11 that's set to true?), and also means you have to remember which parameters corresponds to which option (is setting the edit flag the 9th, 10th, or 11th parameter?) It may also not be very performant, as every function call has to copy 32 booleans from the caller to the function.

Instead, if you defined the function using bit flags like this:

Then you could use bit flags to pass in only the options you wanted:

Not only is this much more readable, it's likely to be more performant as well, since it only involves 2 operations (one logical OR and one parameter copy).

This is one of the reasons OpenGL opted to use bitflag parameters instead of many consecutive booleans.

An RGBA color example

Color display devices such as TVs and monitors are composed of millions of pixels, each of which can display a dot of color. The dot of color is composed from three beams of light: one red, one green, and one blue (RGB). By varying the intensity of the colors, any color on the color spectrum can be made. Typically, the amount of R, G, and B for a given pixel is represented by an 8-bit unsigned integer. For example, a red pixel would have R=255, G=0, B=0. A purple pixel would have R=255, G=0, B=255. A medium-grey pixel would have R=127, G=127, B=127.

When assigning color values to a pixel, in addition to R, G, and B, a 4th value called A is often used. "A" standard for "alpha", and it controls how transparent the color is. If A=0, the color is fully transparent. If A=255, the color is opaque.

R, G, B, and A are normally stored as a 32-bit integer, with 8 bits used for each component:

32-bit RGBA value
bits 31-24 bits 23-16 bits 15-8 bits 7-0
RRRRRRRR GGGGGGGG BBBBBBBB AAAAAAAA
red green blue alpha

The following program asks the user to enter a 32-bit hexadecimal value, and then extracts the 8-bit color values for R, G, B, and A. If you need a reminder about what hexadecimal numbers are, see section 2.8 -- literals.

This produces the output:

Enter a 32-bit RGBA color value in hexadecimal (e.g. FF7F3300): FF7F3300
Your color contains:
255 of 255 red
127 of 255 green
51 of 255 blue
0 of 255 alpha

Note that different machine architectures may store bytes in a different order. RGBA can be stored as ARGB or BGRA depending on the architecture.

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.

Summarizing how to set, unset, toggle, and query bit flags:

To turn a bit on, we use bitwise OR:

To turn a bit off, we use bitwise AND with an inverse bit pattern:

To toggle a bit state, we use bitwise XOR:

To query a bit state, we use bitwise AND:

Quiz

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

5) Given the following program:

5a) Write a line of code to set the article as viewed.
5b) Write a line of code to check if the article was deleted.
5c) Write a line of code to unset the article as a favorite.

Quiz answers

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5a) Show Solution

5b) Show Solution

5c) Show Solution

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

54 comments to 3.8 — Bitwise operators

  • 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;
    }

    • I couldn’t understand the above comment.
      Why he has mentioned of the digit 32 ?

      Please make it clear…

      • In ASCII, upper case and lower case letters are separated by 32 bits. As he says, 65=’A’, 97=’a’. ‘a’-‘A’ = 32. By XORing 32 onto a lower or upper case letter, we can convert it from lower case to upper case or vice versa.

  • 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.

  • 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.

    • Martyn

      You can’t. The original value is lost as the bits are shifted from the end of the value. Bits are memory-less. They don’t remember previous states. You could, however, use a binary representation to refer to a specific location or value, and use bit shifting to point to those different values.

      Binary manipulation allows a fast way to store and manipulate states, as well as performing certain mathematical operations very quickly. Mainly, however, manipulating bits is useful when you are performing a great deal of calculations, where you need a high level of performance, and you’ll find a use for all the bitwise operators here.

      Another example; say you were storing the states of a computer opponent in a video game, and each bit referred to a particular action it could take. 1 for on, 0 for off. If each bit represented a particular action, then 5|6 would result in 0 1 0 0, which would refer to only one action the computer A.I could take, where 5 is its current state, and 6 is the next state it finds itself in. This might seem like an obtuse example, but finite state machines are very commonly used in game A.I.

  • 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.

    • Alex

      Good question. I added a section on using bit flags, as well as an RGBA example of using a 32-bit integer to hold four 8-bit sub-values.

      • MikeM

        Alex, speaking as a guy that has intentionally avoided the concept of bitwise concepts since the dinosaurs roamed I want to say thank you. I get it now. One thing I don’t get is why

        I know I will feel like a dolt, but that is the one part I am unclear on here.

        • Alex

          You’re right, doing the bitwise AND is redundant here, and could be optimized into your second statement.

          I intentionally left the redundancy in because I think it’s easier to understand what it’s doing.

  • 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.

  • 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.

  • Sind

    ~x - flips all the bits of int x.
    Then, is there any option to flip a particular bit of the integer?

    • Alex

      Yes, the bitwise exclusive OR operator (operator^) can flip a particular bit.

      e.g. myflags ^ 0x10; // flip the second to last bit

      • evan

        hi Alex

        how are you doing. hope fine. you are doing a great job.

        I have two questions,

        a) myflags ^|0x10; you wrote in your reply above,   please can you explain, ^|, also which bit was flipped(is it the binary of 0x10)

        b) if you want to toggle 2 bit states, why is it - myflags ^= option4 | option5; and not myflags ^= option4 ^ option5;

        cheers

        • Alex

          1) Typo. I’ve updated the comment.

          2) If you want to toggle 2 bit states, myflags ^= option4 | option5 evaluates as myflags ^= (option4 | option5), where (option4 | option5) turn bit flags 4 and 5 on. Then those are xor’d with myflags. Makes sense logically, right?

          myflags ^= option4 ^ option5 will evaluate to myflags ^= 0, because (option4 ^ option5) evaluates to (1 ^ 1) which is 0. Definitely not what you want.

  • Kevin Wiggins

    I am confused on turning flags on and off. I am new so bare with me.

    correct?

    so myflags is said to have option 4 and option 5 turned on? 0001 0100 is the bit representation for both options being on?

    also is the color example evaluated like this?:

    ff7f 3300
    ff00 0000
    -------
    1100 0000
    or
    ff00 0000

    im confused on how 255 came out of that I know hex ff is 255 but how was that resolved from that?

    • evan

      mate

      this is what ff7f3300 is in binary:
      1111 1111 0111 1111 0011 0011 0000 0000

      and ff000000 is:
      1111 1111 0000 0000 0000 0000 0000 0000

    • Alex

      > so myflags is said to have option 4 and option 5 turned on? 0001 0100 is the bit representation for both options being on?

      0001 0100 is the bit representation for option3 and option5 turned on.

      As evan said, ff7f3300 in binary is 1111 1111 0111 1111 0011 0011 0000 0000

      So when we do this:

      We’re taking 1111 1111 0111 1111 0011 0011 0000 0000 and converting it into 1111 1111 0000 0000 0000 0000 0000 0000, then right shifting the bits 24 places, which gives us just 1111 1111. That number is 255 in binary.

  • Kanchana

    I really enjoyed your tutorial and learnt C++ entirely from this tutorial about an year ago. And now I’m going through it again with updated lessons. thank you for writing such a grate tutorial. I have wrote ‘C’ codes for micro-controllers. Hence I have some bad feeling about these two points.

    a) In ‘Bit Flags’ section we are going save 7 bytes of data using 8 bits of the same byte. but ultimately we have used 9 bytes of data instead of using one byte. I would rather use

    will this make things worse?

    b) In ‘An RGBA color example’ section, I like to write the code as

    because I feel that is much safer. is there any downside? and also need some explanation on

    ‘unsigned int’ bit-wise and with ‘signed int’ literal, expression results an ‘int’ assigned to a ‘unsigned char’ without a cast. :(

    I would like to know your opinion on those few questions. thanks again for this valuable tutorial.

    -Kanchana

    • Alex

      1) In general it’s a good idea to stay away from #define macros where you can (this is covered in section 2.9 -- Symbolic constants and the const keyword.

      As you’ve noted, using bit-flags for a single variable really doesn’t save anything. Bit-flags typically make more sense when you have hundreds or thousands of variables.

      2) Your method works fine. I do mask and shift, you do shift and mask. The end result is the same, and there’s no downside to your method.

      Visual Studio doesn’t throw a warning for these, but some other compilers might complain that casting the results of an unsigned int to an unsigned char is potentially dangerous. You could address this by using static_case to let the compiler know this is intentional:

      • Elpidius

        I would have to agree with Kanchana on the notion of memory. You’ve used 9 bytes instead of 1 byte. Although a const variable shows up in the debugger, using a #define symbolic constant doesn’t take up any memory. If OpenGL used #define symbolic constants, then we can see that #define symbolic constants aren’t all that bad.

        Worst-case scenario, the entire program could be written using const variables (for debugging), then all of the const variables could be replaced with #define symbolic constants (for release).

        • Alex

          Unless you’re pushing the performance limits of your hardware, focusing on memory is probably focusing on the wrong thing. You’re better off focusing on readability, debugability, maintainability, and consistency. Those are much more important than saving a few bytes here and there.

          OpenGL was written before some modern best practices were established. Just because a major library doesn’t something doesn’t mean it’s a good idea -- only that it’s possible.

          Using different code for debug vs release is a bad idea, and a key way that unintended bugs can creep into your code.

  • Malik Imran

    #include "stdafx.h"
    #include <stdio.h>
    #include <cstdlib>
    #include <iostream>
    #include <vector>
    #include <math.h>

    /* For 163 Bits*/
    const char* BASEPOINT_xp = ("%x", "3f0eba16286a2d57ea0991168d4994637e8343e36");
    const char* BASEPOINT_yp = ("%x", "0d51fbc6c71a0094fa2cdd545b11c5c0c797324f1");
    const char* CONSTANT_b = ("%x", "20a601907b8c953ca1481eb10512f78744a3205fd");
    /* For 233 Bits*/    
        const char* BASEPOINT_xp1     = ("%x", "0fac9dfcbac8313bb2139f1bb755fef65bc391f8b36f8f8eb7371fd558b");
        const char* BASEPOINT_yp1     = ("%x", "1006a08a419 03350678e58528bebf8a0beff867a7ca36716f7e01f81052");
        const char* CONSTANT_b1         = ("%x", "066647ede6c332c7f8c0923bb58213b333b20e9ce4281fe115f7d8f90ad");
    /* For 283 Bits*/
        const char* BASEPOINT_xp2     = ("%x", "5f939258db7dd90e1934f8c70b0dfec2eed25b8557eac9c80e2e198f8cdbecd86b12053");
        const char* BASEPOINT_yp2     = ("%x", "3676854fe24141cb98fe6d4b20d02b4516ff702350eddb0826779c813f0df45be8112f4");
        const char* CONSTANT_b2         = ("%x", "27b680ac8b8596da5a4af8a19a0303fca97fd7645309fa2a581485af6263e313b79a2f5");
    /* For 409 Bits*/
        const char* BASEPOINT_xp3     = ("%x", "15d4860d088ddb3496b0c6064756260441cde4af1771d4db01ffe5b34e59703dc255a868a1180515603aeab60794e54bb7996a7");
        const char* BASEPOINT_yp3     = ("%x", "061b1cfab6be5f32bbfa78324ed106a7636b9c5a7bd198d0158aa4f5488d08f38514f1fdf4b4f40d2181b3681c364ba0273c706");
        const char* CONSTANT_b3         = ("%x", "021a5c2c8ee9feb5c4b9a753b7b476b7fd6422ef1f3dd674761fa99d6ac27c8a9a197b272822f6cd57a55aa4f50ae317b13545f");
    /* For 571 Bits*/
        const char* BASEPOINT_xp4     = ("%x", "303001d34b856296c16c0d40d3cd7750a93d1d2955fa80aa5f40fc8db7b2abdbde53950f4c0d293cdd711a35b67fb1499ae60038614f1394abfa3b4c850d927e1e7769c8eec2d19");
        const char* BASEPOINT_yp4     = ("%x", "37bf27342da639b6dccfffeb73d69d78c6c27a6009cbbca1980f8533921e8a684423e43bab08a576291af8f461bb2a8b3531d2f0485c19b16e2f1516e23dd3c1a4827af1b8ac15b");
        const char* CONSTANT_b4         = ("%x", "2f40e7e2221f295de297117b7f3d62f5c6a97ffcb8ceff1cd6ba8ce4a9a18ad84ffabbd8efa59332be7ad6756a66e294afd185a78ff12aa520e4de739baca0c7ffeff7f2955727a");

        int m;

        const char* X1, *Y1, *Z1;
        
    void A_to_LD_Conversion()
    {
    if(m == 163)
        {
        printf("\n\n X1 Contains :: \t");
        X1 = BASEPOINT_xp;
        printf(X1);
        
        printf("\n\n Y1 Contains :: \t");        Y1 = BASEPOINT_yp;
        printf(Y1);

        printf("\n\n Z1 Contains :: \t");
        Z1 = "1";
        printf(Z1);

        }

        else if(m == 233)
        {
        printf("\n\n X1 Contains :: \t");
        X1 = BASEPOINT_xp1;
        printf(X1);
        
        printf("\n\n Y1 Contains :: \t");
        Y1 = BASEPOINT_yp1;
        printf(Y1);

        printf("\n\n Z1 Contains :: \t");
        Z1 = "1";
        printf(Z1);
        
    }

        else if(m == 283)
        {
        printf("\n\n X1 Contains :: \t");
        X1 = BASEPOINT_xp2;
        printf(X1);
        
        printf("\n\n Y1 Contains :: \t");
        Y1 = BASEPOINT_yp2;
        printf(Y1);

        printf("\n\n Z1 Contains :: \t");
        Z1 = "1";
        printf(Z1);
        }

        else if(m == 409)
        {
        printf("\n\n X1 Contains :: \t");
        X1 = BASEPOINT_xp3;
        printf(X1);
        
        printf("\n\n Y1 Contains :: \t");
        Y1 = BASEPOINT_yp3;
        printf(Y1);

        printf("\n\n Z1 Contains :: \t");
        Z1 = "1";
        printf(Z1);
        }

        else if(m == 571)
        {
        printf("\n\n X1 Contains :: \t");
        X1 = BASEPOINT_xp4;
        printf(X1);
        
        printf("\n\n Y1 Contains :: \t");
        Y1 = BASEPOINT_yp4;
        printf(Y1);

        printf("\n\n Z1 Contains :: \t");
        Z1 = "1";
        printf(Z1);
        }

        //else
        //printf("\n\n You Enter Invalid Key Length :: \n\n");
    }

    const char* adder(const char* numb1,const char* numb2,const char* numb3)
    {
        
        numb3 = numb1 + numb2;

    printf("\n\nAddition of two numbers are \t", numb3);
    return numb3;
    }

    char main()
    {
        int i;

    while(m!=163 && m!=233 && m!=283 && m!= 409 && m!=571)
        {
        printf("\n\n Enter the Key length either 163, 233, 283, 409 or 571 bits :: \t");
        scanf("%d",&m);
        }

    A_to_LD_Conversion();

        adder(X1, Y1, X1);

        return 0;
    }

    I am trying to Xor of two arrays which contains data in hexadecimal form.

    At this statement, numb3 = numb1 + numb2; I got error which is (C2110: ‘+’ : cannot add two pointers).

    Please Helped me out.

  • Walid Amin

    Sorry but i think this sentence has a little mistake "If the left operand is an integer type, then operator<< knows it should do its usual bit-shifting behavior."

    As an example:

    it will output 23 (no shift left occured)

    but if you want to do shift left you can do this:

    Thank you

    • Alex

      The sentence is correct.

      In the following code snippet, operator << evaluates from left to right. So this code:

      cout<<2 evaluates first, printing 2, and then then cout<<3 evaluates, printing 3.

      Putting parenthesis changes the precedence, so (2<<3) evaluates first, causing this to do a bit shift and then print the value.

  • programmer, another one

    can we also use this method for question 5C:

    • Alex

      No.

      Using ^= will toggle the state. If it was off, it turns it on. If it was on, it turns it off.

      So this will produce the correct answer only if the article had already been favorited.

      works whether the option was previously favorited or not.

  • David

    In the section on color values, you state "a 4th value called A is often used. "A" standard for "alpha", and it controls how transparent the color is. If A=0, the color is opaque. If A=255, the color is fully transparent."

    This is incorrect.  In graphics programs, A=0 denotes full transparency, while A=255 denotes full opaqueness.  Please correct the error.

  • Vincent

    In the bit flags section, with

    the myflags variable is not initialized so I assume it contains a random byte. So if you do

    how can you know what the result would be? Shouldn’t you have to initialize myflags to contain all zeroes for this to work?

    Thanks.

    • Alex

      You’re correct. Normally we’d initialize myFlags with either 0 or one or more options. I’ve updated the example in the lesson to initialize it to 0.

  • David

    I don’t get why using flags saves memory.
    A boolean takes 1 byte (8 bits) and you waste 7 bits. I got that. But your example has 8 options represented as char type variables, each one holding 1 byte, but you only use 1 bit for each option and pack all selected options in another byte(the myFlags variable) changing the corresponding bit. That makes a total of 9 1-byte variables having 8 of them wasting 7 bits. How is that more efficient than just having 8 boolean variables?

    • Alex

      This question seems to be common enough that I added a new section to the lesson to address it. Have a read and let me know if it answers your concern.

      • David

        It certainly did! I have been programming in java for about 4 years now and i have never encountered a situation i would need to create bit flags. I have used OpenGL ES to create 2 mobile games in android and now that i’m learning C++ i finally understand why it works that way… Thanks a lot! Now i feel really confident about that RPG i always wanted to code.

  • techsavvy....aye

    Just a minor mistake in 3rd paragraph
    " Consequently, bitwise operators have somewhat fallen out of favor, excespt in certain circumstances where maximum optimization is needed"
    excespt instead of exept.

  • techsavvy....aye

    I didn’t understand the bit flags part and how to turn on a particular bit.
    plz help me Alex.I pretty much revised the previous chapters but i can’t assimilate the flag bits part.

    • Alex

      I’m unsure how to help you further here. Turning on a particular bit uses logical OR. So my recommendation is to go back through the logical OR section and make sure you understand how it works, then spend some time convincing yourself that these work:

      regardless of the initial value of the bits in myflags.

Leave a Comment

  

  

  

11 − four =

Put C++ code inside [code][/code] tags to use the syntax highlighter