Skip to main content
Logo image

Section 32.1 Bitwise Operators

C gives us direct access to the individual bits of an integer through a family of bitwise operators:
Table 32.1. Bitwise Operators
Operator Meaning
~ bitwise NOT (negation): flips every bit
<< left shift: shifts all bits left, filling with 0s
>> right shift: shifts all bits right
& bitwise AND: 1 only where both operands have a 1
| bitwise OR: 1 where either operand has a 1
These are entirely different from the logical operators &&, ||, and !, which operate on whole truth values rather than individual bitsโ€” donโ€™t mix them up!
Letโ€™s see the bitwise operators in action. The helper function printBinary() below prints out the binary representation of an unsigned integer, one bit at a time, using the division/remainder approach you may have already seen:

admin.....open in new window

Now letโ€™s add the AND (&) and OR (|) operators to the mix, applied to two numbers at once:

admin.....open in new window

Time to practiceโ€” this time, instead of using division and remainders, use the bitwise operators themselves to read and print each bit directly.

Activity 32.1.

Write a C function that prints the binary representation of an unsigned integer entered by the user. Instead of using division and remainders, you must use bitwise operators (specifically, right-shift and AND) to read and print the bits directly.

admin.....open in new window

Record your code below.

Activity 32.2.

Write a C function that checks whether the \(k\)-th bit of an integer \(n\) is set (1) or not (0). The convention is to count bits from the right, starting at 0. In main(), ask the user to enter an integer as well as the bit position they want to check, call your function to evaluate the bit, and print the conclusion to the screen.

admin.....open in new window

Record your code below.

Activity 32.3.

Write a C program to count the number of 1s in the binary representation of a number. Ask the user for an integer, pass it to a function countBits() that counts the set bits and returns this count, and print the result in main().

admin.....open in new window

Record your code below.