Menu
Coddy logo textTech

Introduction

Lesson 18 of 20 in Coddy's Mathematical Riddles course.

A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method of mathematical expression which uses only two symbols: typically "0" (zero) and "1" (one). [From Wikipedia, the free encyclopedia]

The notations: 110=12, 210=102, 310=112, 410=1002 mean that the numbers 1,2,3 and 4 in decimal numeral system (base-10 numeral system) are equal to 1,10,11 and 100 in binary numeral system.

Counting in binary is similar to counting in any other number system. Beginning with a single digit, counting proceeds through each symbol, in increasing order.

 

To convert from a base-10 integer to its base-2 (binary) equivalent, the number is divided by two. The remainder is the least-significant bit (the most right bit). The quotient is again divided by two; its remainder becomes the next least significant bit. This process repeats until a quotient of one is reached. The sequence of remainders (including the final quotient of one) forms the binary value, as each remainder must be either zero or one when dividing by two. For example, 510 is expressed as 1012, since:

five divided by two is 2 and a reminder of one: 5:2 = 2(1). So the least-significant bit is one. Next, 2:2=1(0). So the next least-significant bit is zero, and the next is one.

 

challenge icon

Challenge

Easy

Write a function calcBinary that get a base-10 integer, and return its equivalent binary number, in string format.

Try doing it without built-in functions

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "solution.h"

int main() {
    int n;
    if (scanf("%d", &n) != 1) n = 0;
    char* r = calcBinary(n);
    printf("%s\n", r);
    return 0;
}

All lessons in Mathematical Riddles

9Binary numbers

Introduction