TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
decimal_to_binary.cpp
Go to the documentation of this file.
1
5
#include <iostream>
6
11
void
method1
(
int
number) {
12
int
remainder, binary = 0, var = 1;
13
14
do
{
15
remainder = number % 2;
16
number = number / 2;
17
binary = binary + (remainder * var);
18
var = var * 10;
19
}
while
(number > 0);
20
std::cout <<
"Method 1 : "
<< binary << std::endl;
21
}
22
27
void
method2
(
int
number) {
28
int
num_bits = 0;
29
char
bit_string[50];
30
31
do
{
32
bool
bit = number & 0x01;
// get last bit
33
if
(bit)
34
bit_string[num_bits++] =
'1'
;
35
else
36
bit_string[num_bits++] =
'0'
;
37
number >>= 1;
// right shift bit 1 bit
38
}
while
(number > 0);
39
40
std::cout <<
"Method 2 : "
;
41
while
(num_bits >= 0)
42
std::cout << bit_string[num_bits--];
// print from MSB to LSB
43
std::cout << std::endl;
44
}
45
46
int
main
() {
47
int
number;
48
std::cout <<
"Enter a number:"
;
49
std::cin >> number;
50
51
method1
(number);
52
method2
(number);
53
54
return
0;
55
}
method2
void method2(int number)
Definition
decimal_to_binary.cpp:27
method1
void method1(int number)
Definition
decimal_to_binary.cpp:11
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
others
decimal_to_binary.cpp
Generated by
1.12.0