當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 Binary轉Decimal用法及代碼示例

在本文中,我們將學習如何編寫 C 程序將給定的二進製數轉換為等效的十進製數。二進製數以基數 2 ( 0, 1 ) 表示,十進製數以基數 10 ( 0-9 ) 表示。

將二進製數轉換為十進製的算法

  • 這個想法是通過執行模運算( % )提取二進製數的最後一位並將其存儲在變量中last_digit並除以 10 從二進製數中刪除最後一位數字。
  • 通過乘法更新小數值last_digit與當前的基值並將其添加到dec_value。
  • 通過將基值乘以 2 來更新基值,以表示下一個數字的下一個 2 的冪。
  • 重複這些步驟,直到處理完二進製數的所有數字。
  • 返回存儲十進製值的變量dec_value。

下圖解釋了如何將 (1010) 轉換為等效的十進製值:

binary to decimal in c

將二進製數轉換為十進製的 C 程序

C


// C program to convert binary to decimal 
#include <stdio.h> 
  
// 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; 
    // Extracting the last digit of the binary number 
    while (temp) { 
        int last_digit = temp % 10; 
        // Removing the last digit from the binary number 
        temp = temp / 10; 
  
        // Multiplying the last digit with the base value 
        // and adding it to the decimal value 
        dec_value += last_digit * base; 
  
        // Updating the base value by multiplying it by 2 
        base = base * 2; 
    } 
  
    // Returning the decimal value 
    return dec_value; 
} 
  
// Driver program 
int main() 
{ 
    int num = 10101001; 
    printf("%d", binaryToDecimal(num)); 
}
輸出
169

複雜性分析

  • 時間複雜度:O(logn)
  • 輔助空間:O(1)

Note: In the above program, we represented a binary number as integer value with base 10 as binary numbers are not directly supported by C language.

請參閱完整文章二進製到十進製轉換程序更多細節!

相關文章



相關用法


注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Convert Binary to Decimal in C。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。