Bitwise Operators in C++

I’ve been perfectly happy with logical operators since I started programming a long, long time ago. That is, your standard AND (&&), OR (||) and NOT (!) operators perform the relevant logical operations so you can say:



But… my understanding of bitwise operators was sketchier. So let’s take a look at the bitwise operators and give them a runthrough to see what they do.

Bitwise Operator List

Let’s start by listing the available bitwise operators:

Bitwise Operator Symbol
& Bitwise AND
| Bitwise Inclusive OR
^ Bitwise Exclusive OR
~ Bitwise NOT
<< Bitwise Left-shift
>> Bitwise Right-shift

So we have 6 basic operators, but we also have the compound versions of these operators, so instead of saying:

We can say:

And they’ll mean the exact same thing – just for completeness, let’s throw those in a table as well:

Bitwise Operator Symbol
&= Bitwise Compound AND
|= Bitwise Compound Inclusive OR
^= Bitwise Compound Exclusive OR
~= Bitwise Compound NOT
<<= Bitwise Compound Left-shift
>>= Bitwise Compound Right-shift

So now that we have these operators, let’s see what we can do with them…

Continue reading Bitwise Operators in C++

How-to: Overload the C++ function operator()

I’m working my way through the first few chapters of James Reinders’ Intel Threading Building Blocks book, and its a little bit hard going. As much as I’m enjoying the mental exercise of thinking in parallel, when it actually comes to the coding they use a lot of function operator (i.e. operator()) overloading, and I’m not so familiar with it. As much as I’ve overloaded operators before so you could, for example, add two Fruit objects together and get their weight, or multiply an Employee->monthlySalary by 12 to get their yearly wage, I’d never overloaded the function operator itself, so wasn’t sure what was really going on in the code.

To fix this, I’ve knocked together a super-simple example to show how it works:

Which gives the output:

So, that’s how it works. Straight forward enough.

Another example, taken from the Function object wikipedia page:

Counting from 10 to 20 has never been funner =D