The bitwise operators

C++ provides 6 bit manipulation operators, often called bitwise 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 |

Author's 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 actual programs, the number of bits used is based on the size of the object (e.g. a 2 byte object would store 16 bits).

For readability, we’ll also omit the 0b prefix outside of code examples (e.g. instead of 0b0101, we’ll just use 0101).

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 the bits of, and the right operand is an integer number of bits to shift left by.

So when we say `x << 1`

, we are saying "shift the bits in the variable x left by 1 place". New bits shifted in from the right side receive the value 0.

0011 << 1 is 0110

0011 << 2 is 1100

0011 << 3 is 1000

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.

1100 >> 1 is 0110

1100 >> 2 is 0011

1100 >> 3 is 0001

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

Here's an example of doing some bit shifting:

1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <bitset> #include <iostream> int main() { std::bitset<4> x { 0b1100 }; std::cout << x << '\n'; std::cout << (x >> 1) << '\n'; // shift right by 1, yielding 0110 std::cout << (x << 1) << '\n'; // shift left by 1, yielding 1000 return 0; } |

This prints:

1100 0110 1000

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

Warning

Prior to C++20, don't shift a signed integer (and even then, it's probably still better to use unsigned)

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 std::cout to output text. Consider the following program:

1 2 3 4 5 6 7 8 9 10 11 |
#include <bitset> #include <iostream> int main() { unsigned int x { 0b0100 }; x = x << 1; // use operator<< for left shift std::cout << std::bitset<4>{ x }; // use operator<< for output return 0; } |

This program prints:

1000

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 **overloaded** (provided an alternate definition for) operator<< that does console output rather than bit shifting.

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 overloaded to do output. If the left operand is an integral type, then operator<< knows it should do its usual bit-shifting behavior.

The same applies for operator>>.

Note that if you're using operator << for both output and left shift, parenthesization is required:

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <bitset> #include <iostream> int main() { std::bitset<4> x{ 0b0110 }; std::cout << x << 1 << '\n'; // print value of x (0110), then 1 std::cout << (x << 1) << '\n'; // print x left shifted by 1 (1100) return 0; } |

This prints:

01101 1100

The first line prints the value of x (0110), and then the literal 1. The second line prints the value of x left-shifted by 1 (1100).

We will talk more about operator overloading in a future section, including discussion of how to overload 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.

Flipping 4 bits:

~0100 is 1011

Flipping 8 bits:

~0000 0100 is 1111 1011

In both the 4-bit and 8-bit cases, we start with the same number (binary 0100 is the same as 0000 0100 in the same way that decimal 7 is the same as 07), but we end up with a different result.

We can see this in action in the following program:

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << std::bitset<4>{ ~0b0100u } << ' ' << std::bitset<8>{ ~0b0100u }; return 0; } |

This prints:

1011 11111011

Bitwise OR

Bitwise OR (|) works much like its *logical OR* counterpart. However, instead of applying the *OR* to the operands to produce a single result, *bitwise OR* applies to each bit! For example, consider the expression `0b0101 | 0b0110`

.

To do (any) bitwise operations, it is easiest to line the two operands up like this:

0 1 0 1 OR 0 1 1 0

and then apply the operation to each *column* of bits.

If you remember, *logical OR* evaluates to *true (1)* if either the left, right, or both operands are *true (1)*, and *0* otherwise. *Bitwise OR* evaluates to *1* if either the left, right, or both bits are *1*, and *0* otherwise. Consequently, the expression evaluates like this:

0 1 0 1 OR 0 1 1 0 ------- 0 1 1 1

Our result is 0111 binary.

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0101 } | std::bitset<4>{ 0b0110 }); return 0; } |

This prints:

0111

We can do the same thing to compound OR expressions, such as `0b0111 | 0b0011 | 0b0001`

. If any of the bits in a column are *1*, the result of that column is *1*.

0 1 1 1 OR 0 0 1 1 OR 0 0 0 1 -------- 0 1 1 1

Here's code for the above:

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0111 } | std::bitset<4>{ 0b0011 } | std::bitset<4>{ 0b0001 }); return 0; } |

This prints:

0111

Bitwise AND

Bitwise AND (&) works similarly to the above. *Logical AND* evaluates to true if both the left and right operand evaluate to *true*. *Bitwise AND* evaluates to *true (1)* if both bits in the column are *1*. Consider the expression `0b0101 & 0b0110`

. Lining each of the bits up and applying an AND operation to each column of bits:

0 1 0 1 AND 0 1 1 0 -------- 0 1 0 0

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0101 } & std::bitset<4>{ 0b0110 }); return 0; } |

This prints:

0100

Similarly, we can do the same thing to compound AND expressions, such as `0b0001 & 0b0011 & 0b0111`

. If all of the bits in a column are 1, the result of that column is 1.

0 0 0 1 AND 0 0 1 1 AND 0 1 1 1 -------- 0 0 0 1

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0001 } & std::bitset<4>{ 0b0011 } & std::bitset<4>{ 0b0111 }); return 0; } |

This prints:

0001

Bitwise XOR

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 its operands is *true (1)*. If neither or both are true, it evaluates to *0*. Consider the expression `0b0110 ^ 0b0011`

:

0 1 1 0 XOR 0 0 1 1 ------- 0 1 0 1

It is also possible to evaluate compound XOR expression column style, such as `0b0001 ^ 0b0011 ^ 0b0111`

. 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 XOR 0 0 1 1 XOR 0 1 1 1 -------- 0 1 0 1

Bitwise assignment operators

Similar to 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;`

.

1 2 3 4 5 6 7 8 9 10 11 |
#include <bitset> #include <iostream> int main() { std::bitset<4> bits { 0b0100 }; bits >>= 1; std::cout << bits; return 0; } |

This program prints:

0010

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.

In the next lesson, we'll explore how these operators can be used in conjunction with bit masks to facilitate bit manipulation.

Quiz time

Question #1

a) What does 0110 >> 2 evaluate to in binary?

b) What does the following evaluate to in binary: 0011 | 0101?

c) What does the following evaluate to in binary: 0011 & 0101?

d) What does the following evaluate to in binary (0011 | 0101) & 1001?

Question #2

A bitwise rotation is like a bitwise shift, except that any bits shifted off one end are added back to the other end. For example 0b1001 << 1 would be 0b0010, but a left rotate by 1 would result in 0b0011 instead. Implement a function that does a left rotate on a std::bitset<4>. For this one, it's okay to use test() and set().

The following code should execute:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <bitset> #include <iostream> // "rotl" stands for "rotate left" std::bitset<4> rotl(std::bitset<4> bits) { // Your code here } int main() { std::bitset<4> bits1{ 0b0001 }; std::cout << rotl(bits1) << '\n'; std::bitset<4> bits2{ 0b1001 }; std::cout << rotl(bits2) << '\n'; return 0; } |

and print the following:

0010 0011

O.3 -- Bit manipulation with bitwise operators and bit masks |

Index |

O.1 -- Bit flags and bit manipulation via std::bitset |

Hey Alex,

There is a mistake in second line of second paragraph under section "Bitwise left shift (<<) and bitwise right shift (>>) operators".

In line " The left operand is the expression to shift, and the right operator is an integer number of bits to shift by.", it should be 'right operand' instead of 'right operator'.

Thanks for building this wonderful website.

Thanks for pointing out the error. It has been fixed.

Great work! I just wanted to thank you for all these information you prepared!

Hello,

I tried to use the bitwise NOT (~) to integers of different sizes to see what would happen. However, I cannot seem to get a proper response. Code below:

Any ideas welcome

It's working fine -- it's just printing the results as an integer rather than as a series of bits. If you write a function to print out an integer in binary, you can send 4 and ~4 to it and see that they're bitwise inverses of each other.

Your advertising on this site is ridiculous. I can hardly read anything without complete frustration. My browser just jumps the the video at the bottom at the article every 10 seconds. Jesus..

There's a bug in the embedded video player served up by Google right now for some users. I've switched the offending ad block to a non-video format to try and work around this for the time being. My apologies for the disruption.

TYPO: ...if one and only one of it's operands...

it's = its.

Fixed. I hate it's vs its.

Another reason why you might find this useful is if you do any microcontroller programming, especially now that maker stuff, Arduino and Raspberry Pi GPIO is so popular, this is a great resource for when you start setting those pins and ports on you Attiny or whatever you MCU of choice is.

hi

how to multiply two varialbe with << ???

Multiplies x by 2 to the power of y.

But generally you shouldn't do this. It's better to do x *= y to make your intent clear, and reserve << for cases where you want to shift bits.

ok, tnx

i had to use bitwise operation, because my teacher wanted

Typo:

"Bitwise AND evaluates to true if both bits in the column are 1) Consider the expression..."

Thanks, typo fixed!

Wow! Equating bitwise and logical operators finally helped me understand things! Why don't any other tutorials teach that? Thanks!

What happens when you mismatch the sizes of the variables?

From what i've tested out it seems like the 8 bit integer gets promoted to 16 bits and the extra bits are filled with zeroes before the expression is evaluated.

Also, it seems like if you put an incorrect size of bits for the variable it will add/remove bits from the left. So

becomes 0, and

is 64.

One thing i'm wondering though is if it only overwrites the part you specified.

Say you create x uninitialized,

and that memory address has some garbage like 0b1111'1111.

Then you say:

Does it only overwrite the part you specified?

ie. now x = 0b1101'0000.

what? this is supposed to be hard? I'm half way in and having no problems understanding this at all

Bitwise operators are handy for resource scheduling applications. Suppose we want to find a 30 minute time slot when the conference room, the projector and the instructor are all available.

Each of these 3 resources can be kept track of using 16-bit integer bitmasks where each bit corresponds to a 30 minute time slot of the 8 hour day. Each bit is set to 0 if the resource is not available then or 1 if it is available.

The 3 bitmasks can be combined using the bitwise AND to easily find out which time slots are available to all 3 resources.

Hi, 3 << 3 = 11000, which 24 I think.

Added another reminder to the lesson that the examples are using 4-bit numbers.

Small mistake:

3 << 3 = 1000 = 8

3 * 2**3 = 24

not 8

I understand 1000 is equal to 8, but still I think it can be quite confusing if people start to enter 3 << 3 in C++ and see the results.

Perhaps, though you're the first to comment about it. Anybody else find this confusing?

I didn't quite get the issue until I wrote it and ran it.

Here's how I got back to a somewhat canned, 4 bit example:

As noted in the lesson, we're using 4 bit numbers for simplicity. The 1 bit representing decimal 16 is shifted off the end of the number and lost.

You would be correct if we were using numbers with 5 or more bits. :)

I think I just discovered which lesson it was that helped me decide to give up trying to learn C++ the last time :-P.

I'm gonna tough it out but WOW is this bitstuff confusing. First I was thinking: Gotta think with functions, now it's 'gotta think with binary'. With bytes all over the place, how do I know my 'tampering' is dealing with the same byte? Or is this a matter of manipulating specific bits instead of dealing with entire bytes?

These bit lessons tend to be challenging for a lot of people. Don't get stuck here. If you can't figure it out, move on. This stuff isn't that important in the grand scheme of things, and you can always come back to it later.

can i ask how exactly is this used ? we can shift bits left and right eventually changing the decimal value they represent but how does this save memory space ? base on the above introduction to this lesson i kept thinking this maybe a lesson on how to fit two bool values in 1 byte to prevent bits spaces from getting wasted. but i still dont know how does it affect our data ? for example i have a variable isOK which is a bool type variable how do i use bitwise to it and how does it make this variable save space or free space for other bool type variables that i may use ?

Shifting itself doesn't save space, it's just one tool to manipulate individual bits within a byte.

With regards to space savings, the key here is to recognize that computer architectures generally only allow byte-level addressing, meaning you can only read/write memory in blocks of 1 byte. That means if you need less than one byte, you still have to use one byte, because that's the minimum that can be assigned an address. This can result in wasted space (unused bits).

However, by using bit-level manipulators, we can partition a single byte into multiple sub-values. In this way, we can "pack" multiple bit-sized values into a single byte, improving our utilization of that byte. If we only have 1 boolean, we don't get any savings, because we have to use at minimum one byte. We only accrue savings if we can pack multiple values into a single byte.

like for example i am planning on creating and using 2 bool variables "attacked" and "defended" both of which only requires 0 1 values. how do i make use of bit manipulators to store these two in a table with compressing them both in a single byte ?

You'd define one 8-bit value, and then use bitwise operators to access the individual bits. This is pretty well covered in the next lesson on Bit flags and bit masks. Attacked and Defended would be bit flags.

That said, bit flags and this kind of compression make your code significantly more complex. It's not worth doing unless you need to squeeze every drop of memory out of your system.

oh I finally got it thanks ! using only 1 variable ( 8 bits ) i kept thinking multiple variables shoopiiiddd. so only 1 variable to use and i can use bit manipulators to switch off/on each bit of the 8 bit variable which will then equate to a maximum of 8 switches. 1 8bit variable for almost 8 bools. that clarified it thanks.

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

Actually, they are some domains where bitwise operators are just needed, even for non optimized programs. For instance, a lot of cryptographic algorithms are bloated with bitwise operations: just take a look at how MD5, SHA-1 or AES work. ;-)

True, crypto programs use tons of bitwise operators! That's a good example.

So if

14 >> 1 = 1110 => 0111 = 7 = 14/2^1

16 >> 2 = 10000=>00100 = 4 = 16/2^2

24 >> 3 = 11000=>00011 = 3 = 24/2^3

Then so long as bits aren't lost off the end the bit shifting operators also work to either multiply or divide by 2 raised to the power of the amount of bits shifted by

I assume this is never recommended but just the way that stuff works in any base

While you can multiple or divide by 2 by shifting bits, it isn't recommended that you do this manually. It's better to be clear about your intent, and then let the compiler handle the optimization of this for you.

I came across exactly what we had been learning in this lesson over the week-end, when I looked up how to turn off the tool tip in windows. There was some discussion about it on a forum and someone had came across an entry in the registry, using flags set in hex, exactly like Alex had show us, but the guy had added the caveat that it look awfully complicated and should probably be left alone. I could see straight away that bit 7 needed to be turned off to switch off the tool tips. The number was a 2 byte hex number, and using the calculator that comes with Windows in programmer mode and hex number system, it also shows you the number in binary underneath the hex, so I was able to share with the forum the number in hex that the mask needed to be changed to to turn off the feature and felt very pleased with myself, lol.

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

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.

~x - flips all the bits of int x.

Then, is there any option to flip a particular bit of the integer?

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

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

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

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.

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.

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 &= !!

Is there a logical XOR operator.

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.

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

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.

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

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

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.

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.

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.

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;

}

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

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.

correction

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

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

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.

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!