原文: https://www.programiz.com/cpp-programming/examples/binary-decimal-convert

在此示例中,您将学习通过创建用户定义的函数将二进制数转换为十进制,以及将十进制数手动转换为二进制。

要理解此示例,您应该了解以下 C++ 编程主题:


访问此页面以了解如何将二进制数转换为十进制

示例 1:将二进制数转换为十进制

  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. int convertBinaryToDecimal(long long);
  5. int main()
  6. {
  7. long long n;
  8. cout << "Enter a binary number: ";
  9. cin >> n;
  10. cout << n << " in binary = " << convertBinaryToDecimal(n) << "in decimal";
  11. return 0;
  12. }
  13. int convertBinaryToDecimal(long long n)
  14. {
  15. int decimalNumber = 0, i = 0, remainder;
  16. while (n!=0)
  17. {
  18. remainder = n%10;
  19. n /= 10;
  20. decimalNumber += remainder*pow(2,i);
  21. ++i;
  22. }
  23. return decimalNumber;
  24. }

输出

  1. Enter a binary number: 1111
  2. 1111 in binary = 15

访问此页面以了解如何将十进制数转换为二进制

示例 2:将十进制数转换为二进制

  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. long long convertDecimalToBinary(int);
  5. int main()
  6. {
  7. int n, binaryNumber;
  8. cout << "Enter a decimal number: ";
  9. cin >> n;
  10. binaryNumber = convertDecimalToBinary(n);
  11. cout << n << " in decimal = " << binaryNumber << " in binary" << endl ;
  12. return 0;
  13. }
  14. long long convertDecimalToBinary(int n)
  15. {
  16. long long binaryNumber = 0;
  17. int remainder, i = 1, step = 1;
  18. while (n!=0)
  19. {
  20. remainder = n%2;
  21. cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ", Quotient = " << n/2 << endl;
  22. n /= 2;
  23. binaryNumber += remainder*i;
  24. i *= 10;
  25. }
  26. return binaryNumber;
  27. }

输出

  1. Enter a decimal number: 19
  2. Step 1: 19/2, Remainder = 1, Quotient = 9
  3. Step 2: 9/2, Remainder = 1, Quotient = 4
  4. Step 3: 4/2, Remainder = 0, Quotient = 2
  5. Step 4: 2/2, Remainder = 0, Quotient = 1
  6. Step 5: 1/2, Remainder = 1, Quotient = 0
  7. 19 in decimal = 10011 in binary