CS253 Bit Manipulation
C++ can do bit manipulation:
&
), or (|
), exclusive-or (^
)
<<
), shift right (>>
)
&=
, |=
, ^=
, <<=
, >>=
)
0377
)
0x3FF
)
0b1010110111
)
// 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.
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')
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
cout << hex << 126 << '\n'; cout << hex << (126 & ~0xF) << '\n';
7e 70
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.
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
Modified: 2017-02-27T13:16 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |