-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
binary_to_decimal.c
68 lines (61 loc) · 2.13 KB
/
binary_to_decimal.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* @brief Converts a number from [Binary to Decimal](https://en.wikipedia.org/wiki/Binary-coded_decimal).
* @details
*
* Binary to decimal conversion is a process to convert a number
* having a binary representation to its equivalent decimal representation.
*
* The base of both number systems is different.
* Binary number system is base 2 number system while decimal number system is base 10 number system.
* The numbers used in binary number system are 0 and 1 while decimal number system has numbers from 0 to 9.
* The conversion of binary number to decimal number is done by multiplying
* each digit of the binary number, starting from the rightmost digit, with the power of 2 and adding the result.
*
* @author [Anup Kumar Pawar](https://github.com/AnupKumarPanwar)
* @author [David Leal](https://github.com/Panquesito7)
*/
#include <stdio.h> /// for IO operations
#include <assert.h> /// for assert
#include <math.h> /// for pow
#include <inttypes.h> /// for uint64_t
/**
* @brief Converts the given binary number
* to its equivalent decimal number/value.
* @param number The binary number to be converted
* @returns The decimal equivalent of the binary number
*/
int convert_to_decimal(uint64_t number) {
int decimal_number = 0, i = 0;
while (number > 0) {
decimal_number += (number % 10) * pow(2, i);
number = number / 10;
i++;
}
return decimal_number;
}
/**
* @brief Self-test implementations
* @returns void
*/
static void tests() {
assert(convert_to_decimal(111) == 7);
assert(convert_to_decimal(101) == 5);
assert(convert_to_decimal(1010) == 10);
assert(convert_to_decimal(1101) == 13);
assert(convert_to_decimal(100001) == 33);
assert(convert_to_decimal(10101001) == 169);
assert(convert_to_decimal(111010) == 58);
assert(convert_to_decimal(100000000) == 256);
assert(convert_to_decimal(10000000000) == 1024);
assert(convert_to_decimal(101110111) == 375);
printf("All tests have successfully passed!\n");
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
tests(); // run self-test implementations
return 0;
}