CS253: Software Development with C++

Spring 2018

Bit Manipulation

See this page as a slide show

CS253 Bit Manipulation

Refresher

C++ can do bit manipulation:

Displaying values in other bases

// Sorry, no bin
cout << (127 & 0xfe) << '\n';
cout << hex << (127 & 0xfe) << '\n';
cout << oct << (127 & 0xfe) << '\n';
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:

int n = 32;
cout << hex << n << '\n';
n |= 02;
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

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:50

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