Integer Binary

Print the binary representation of an integer.

A simple approach is to use bitwise operations. First get the number of bits, then starting from the leftmost bit and moving to the right, mask each individual bit with 1. If the bit is a 1, print 1 and if the bit is 0, print 0.

The function runs in O(1) time for any int value. Every int value, large or small, will have the same number of bits.

void binary(int n) {
  int bits = sizeof(n) * CHAR_BIT

  do {
    bits--
    int bit = (n >> bits) & 1
    print(bit)
  } while (bits > 0);
}

Scroll to top