From 776832b84b4e584633f6ad55753c39ca99cf59d8 Mon Sep 17 00:00:00 2001 From: Prakhar Dubey Date: Wed, 28 Oct 2020 13:31:19 +0530 Subject: [PATCH] Create binary_to_decimal.cpp hello, I am new to open source, trying to contribute, and i am participating in hactoberfest 2020, i'd love if you merge my pull request and label it as hacktoberfest-accepted, --- Conversions/C:C++/binary_to_decimal.cpp | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Conversions/C:C++/binary_to_decimal.cpp diff --git a/Conversions/C:C++/binary_to_decimal.cpp b/Conversions/C:C++/binary_to_decimal.cpp new file mode 100644 index 00000000..587e66c6 --- /dev/null +++ b/Conversions/C:C++/binary_to_decimal.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +// Function to convert binary to decimal +int binaryToDecimal(int n) +{ + int num = n; + int dec_value = 0; + + // Initializing base value to 1, i.e 2^0 + int base = 1; + + int temp = num; + while (temp) { + int last_digit = temp % 10; + temp = temp / 10; + + dec_value += last_digit * base; + + base = base * 2; + } + + return dec_value; +} + +// Driver program to test above function +int main() +{ + int num = 10101001; + + cout << binaryToDecimal(num) << endl; +}