We'll learn later that C++ has many library or API functions for formatting output. There isn't anything special about these functions - they just convert numbers into characters or strings of characters. As an example of bitwise operators, we'll write a simple program to display an integer in binary, a string of bits.
Caution
Integers, including unsigned integers, span two to eight bytes of memory, and the underlying computer hardware determines their order. The solution presented here works on a little endian computer (e.g., Intel or AMD). It does not work on big endian hardware.
Solution
2 2 2 1 1
8 4 0 6 2 8 4 0
1010 0000 1011 0000 1100 0000 1101 0000
a 0 b 0 c 0 d 0
Printing in binary example. Let's imagine that we run the above program and enter the hexadecimal number a0b0c0d0 (you may use upper or lower case letters). To create a test case and to make it easier for us to follow the operations that take place in the body of the for-loop, we manually convert the hexadecimal number to binary. If we use the table shown in Figure 5, the conversion is straightforward.
The input number in both binary and hexadecimal. We break the binary number into 4-bit groups or nibbles to make it easier to read. The numbers highlighted in yellow are the bit positions - most significant to the left and least significant to the right.
The for-loop runs through 32 iterations, from i = 31 through i = 0. (b) illustrates how the bit-shift operation affects the value in number when i = 4.
The parentheses cause the bit-shift operation to occur first. (c) illustrates the bitwise-AND with 1 (displayed in binary as 31 leading 0s and one 1-bit). The bitwise-AND operation masks out (0 & x = 0) the left-most 31 bits; the right-most bit is passed through (1 & x = x).