TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
decimal_to_binary.cpp File Reference

Function to convert decimal number to binary representation. More...

#include <iostream>
Include dependency graph for decimal_to_binary.cpp:

Go to the source code of this file.

Functions

void method1 (int number)
 
void method2 (int number)
 
int main ()
 

Detailed Description

Function to convert decimal number to binary representation.

Definition in file decimal_to_binary.cpp.

Function Documentation

◆ main()

int main ( void )

Definition at line 46 of file decimal_to_binary.cpp.

46 {
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}
void method2(int number)
void method1(int number)

◆ method1()

void method1 ( int number)

This method converts the bit representation and stores it as a decimal number.

Definition at line 11 of file decimal_to_binary.cpp.

11 {
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}

◆ method2()

void method2 ( int number)

This method stores each bit value from LSB to MSB and then prints them back from MSB to LSB

Definition at line 27 of file decimal_to_binary.cpp.

27 {
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}