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

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

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


将二进制转换为十进制的程序

  1. #include <math.h>
  2. #include <stdio.h>
  3. int convert(long long n);
  4. int main() {
  5. long long n;
  6. printf("Enter a binary number: ");
  7. scanf("%lld", &n);
  8. printf("%lld in binary = %d in decimal", n, convert(n));
  9. return 0;
  10. }
  11. int convert(long long n) {
  12. int dec = 0, i = 0, rem;
  13. while (n != 0) {
  14. rem = n % 10;
  15. n /= 10;
  16. dec += rem * pow(2, i);
  17. ++i;
  18. }
  19. return dec;
  20. }

输出

  1. Enter a binary number: 110110111
  2. 110110111 in binary = 439

将十进制转换为二进制的程序

  1. #include <math.h>
  2. #include <stdio.h>
  3. long long convert(int n);
  4. int main() {
  5. int n;
  6. printf("Enter a decimal number: ");
  7. scanf("%d", &n);
  8. printf("%d in decimal = %lld in binary", n, convert(n));
  9. return 0;
  10. }
  11. long long convert(int n) {
  12. long long bin = 0;
  13. int rem, i = 1, step = 1;
  14. while (n != 0) {
  15. rem = n % 2;
  16. printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, rem, n / 2);
  17. n /= 2;
  18. bin += rem * i;
  19. i *= 10;
  20. }
  21. return bin;
  22. }

输出

  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