21xrx.com
2024-09-20 00:18:41 Friday
登录
文章检索 我的文章 写文章
C++实现二进制转十进制的代码
2023-06-23 13:06:18 深夜i     --     --
C++ 二进制 十进制 实现 代码

Binary to Decimal Conversion using C++ Code

Binary to decimal conversion is a common operation in computer programming. It is a fundamental operation in digital electronics and computer science. C++ provides a simple and efficient way to implement this operation. In this article, we will discuss how to implement binary to decimal conversion using C++ code.

The binary to decimal conversion process involves multiplying each digit in the binary number by a power of 2 and adding up the results. For example, to convert the binary number 1011 to decimal, we calculate:

(1 x 2^3) + (0 x 2^2) + (1 x 2^1) + (1 x 2^0) = 8 + 0 + 2 + 1 = 11

Here is the C++ code for binary to decimal conversion:

#include

#include

using namespace std;

int main()

{

  long long binaryNumber;

  cout << "Enter a binary number: ";

  cin >> binaryNumber;

  int decimalNumber = 0, i = 0, remainder;

  while (binaryNumber != 0)

  {

    remainder = binaryNumber % 10;

    binaryNumber /= 10;

    decimalNumber += remainder * pow(2, i);

    ++i;

  }

  cout << "Decimal Number = " << decimalNumber;

  return 0;

}

Let's understand the logic of the code. We first declare a variable to store the binary number input by the user. Then we prompt the user to enter the binary number.

Next, we declare a variable to store the decimal number and initialize it to 0. We also declare a variable i to keep track of the power of 2.

In the while loop, we get the remainder of dividing the binary number by 10 and store it in a variable called remainder. We then divide the binary number by 10 to remove the last digit. We then add the product of the remainder and the power of 2 to the decimal number. We then increment i by 1.

We repeat this process until the binary number becomes 0.

Finally, we print the decimal number.

Conclusion

Binary to decimal conversion is a basic operation in computer programming. It is essential to understand this process to work with binary numbers in computer programs. C++ provides an easy way to implement this operation using simple code. By understanding the logic behind the code, you can modify the code according to your requirements.

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复