03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

28 CHAPTER 2. <strong>C++</strong> BASICS<br />

The bitwise operations can be used to characterize properties in a very compact <strong>for</strong>m as in the<br />

following example:<br />

#include <br />

int main ()<br />

{<br />

int concave = 1, monotone = 2, continuous = 4;<br />

int f is = concave | continuous;<br />

std::cout ≪ ”f is ” ≪ f is ≪ std::endl;<br />

std::cout ≪ ”Is f concave? (0 means no, 1 means yes) ”<br />

≪ (f is & concave) ≪ std::endl;<br />

f is = f is | monotone;<br />

f is = f is ˆ concave;<br />

std::cout ≪ ”f is now ” ≪ f is ≪ std::endl;<br />

return 0 ;<br />

}<br />

Line 5 introduces three properties that can be combined arbitrarily. The numbers are powers<br />

of two so that their binary representations contain a single 1-bit respectively. In line 7 we used<br />

bitwise OR to combine two properties. Bitwise AND allows <strong>for</strong> masking single or multiple bits<br />

as shown in line 11. In line 13 an additional property is set with bitwise OR. Bitwise exclusive<br />

OR (XOR) like in line 14 allows <strong>for</strong> toggling a property. Operating systems and hardware driver<br />

use this style of operations exhaustively. But it needs some practice to get used to it.<br />

Shift operations provide an efficient way to multiply with or divide by powers of 2 as shown in<br />

the following code:<br />

int i = 78;<br />

std::cout ≪ ”i ∗ 8 is ” ≪ (i ≪ 3)<br />

≪ ”, i / 4 is ” ≪ (i ≫2) ≪ std::endl;<br />

Obviously, that needs some familiarization as well.<br />

On the per<strong>for</strong>mance side, processors are today quite fast in multiplying integers so that you<br />

will not see a big per<strong>for</strong>mance boost when replacing your products by left shifts. Division is<br />

still a bit slow and a right shift can make a difference. Even then the price of this source code<br />

obfuscation is only justified if the operation is critical <strong>for</strong> the overall per<strong>for</strong>mance of your entire<br />

application.<br />

2.3.4 Compound assignment<br />

The compound assignment operators apply an arithmetic operation to the left and right-hand<br />

side and store the result in the left hand side.<br />

There operators are +=, −=, ∗=, /=, %=, ≫=, ≪=, &=, ˆ=, and |=.<br />

The statement a+=b is equal to the statement a=a+b.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!