CS253: Software Development with C++

Spring 2019

Bit Manipulation

Show Lecture.BitManipulation as a slide show.

CS253 Bit Manipulation

Kat Dennings as Max Black

Refresher

C++ bit-manipulation tools:

Displaying values in other bases

// Still no binary output‽
cout << (0b10000001 ^ 03) << '\n';
cout << (127 & 0xfe) << '\n';
cout << hex << (127 & 0xfe) << '\n';
cout << oct << (127 & 0xfe) << '\n';
130
126
7e
176

I/O manipulators such as hex and oct are “sticky”; they persist until changed.

Precedence matters

cout << (1|2) << '\n';
3

However, the binary bitwise operators are low precedence:

cout << 1|2 << '\n';
c.cc:1: error: no match for 'operator|' in '
   std::cout.std::basic_ostream<char>::operator<<(1) | (2 << 10)' (operand 
   types are 'std::basic_ostream<char>' and 'int')

Setting a bit

int n = 32;
cout << hex << n << '\n';
cout << hex << (n|02) << '\n';
20
22

Or, using assignment and C++14’s binary literals:

int n = 32;
cout << hex << n << '\n';
n |= 0b10;
cout << hex << n << '\n';
20
22

Clearing bits

cout << hex << 126 << '\n';
cout << hex << (126 & ~0xF) << '\n';
7e
70

Testing bits

for (char c='A'; c<'N'; c++)
    if (c & 0x01)
        cout << "'" << c << "' (" << int(c) << ") is odd.\n";
    else
        cout << "'" << c << "' (" << int(c) << ") is even.\n";
'A' (65) is odd.
'B' (66) is even.
'C' (67) is odd.
'D' (68) is even.
'E' (69) is odd.
'F' (70) is even.
'G' (71) is odd.
'H' (72) is even.
'I' (73) is odd.
'J' (74) is even.
'K' (75) is odd.
'L' (76) is even.
'M' (77) is odd.

Shifting

int n = 42;
cout << oct << n << '\n';
n >>= 1;
cout << n << '\n';
n >>= 2;
cout << n << '\n';
n >>= 1;
cout << n << '\n';
n >>= 1;
cout << n << '\n';
n >>= 1;
cout << n << '\n';
52
25
5
2
1
0

Badness

// Don’t shift too far:
cout << (1<<32) << '\n';
c.cc:2: warning: left shift count >= width of type
0
// Don’t shift negatively:
cout << (0b1000 << -1) << '\n';
c.cc:2: warning: left shift count is negative
4
// Shifting negative values right is implementation-defined:
cout << (-1 >> 1) << '\n';
-1

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-12-29T15:17

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building