Getting started #
Make sure to set-up first.
1. Write a function that prints a 32-bit integer in binary #
In C there is no way to use printf()
such that it prints a variable, such as an int
or unsigned int
in its stored binary format. However, printing in binary comes in really handy sometimes. The goal is to write a function that takes an unsigned int x
as input, and prints it in binary:
#include <stdio.h>
// <-- write print_binary(x) here
int main() {
unsigned x = 27;
print_binary(x); // 00000000 ... 00011011
return 0;
}
To do so, first try to code a way to print a single bit of x
. This requires the bitwise AND operator &
, which is defined as: a & b
returns a number that has a $1$ in a bit $j$ iff. both a
and b
have a $1$ in bit $j$. Otherwise the $j$-th bit is zero.
To print the $i$-th bit of $x$:
- Make a number
mask
with zeros everywhere, but a $1$ in position $i$, usingmask = 1 << i
. - Apply the
&
between the mask and the inputx
. - Use the outcome to decide if bit $i$ is $0$ or $1$.
The solution is now to loop all the bits in x
, and print them one by one.
Solution
One way to write this function is:
void print_binary(unsigned int x) {
int mask;
for (int i = 31; i >= 0; i--) {
mask = 1 << i;
if ((x & mask) == 0) {
printf("0");
} else {
printf("1");
}
if (i % 8 == 0 && i > 0)
printf(" ");
}
printf("\n");
}
- The function works well with all 32-bit inputs, but the input has to be cast to 32-bit first.
- It doesn’t work for any other types.
A compact way to write this function is:
void print_binary(unsigned x) {
for (unsigned m = 1 << 31; m > 0; m >>= 1)
printf("%d", (x & m) > 0)
}
Note:
mask >>= 1
is the same asmask = mask >> 1
.(x & mask) > 0
returns an integer (in C, logical operators, like>
, result in an integer $0$ or $1$) and not in a boolean.