2015-10-13 31 views
1

我正在尋找將浮點數轉換爲C語言的十進制表示法的最佳方法。我將嘗試給出一個例子:用戶在IEEE754中引入一個數字(1 1111111 10101 ...),程序必須返回十進制表示(例如25.6)
我嘗試過使用掩碼和按位運算,但是我沒有得到任何邏輯結果。IEEE 754到C語言的十進制數

+1

爲什麼不使用標準庫函數? – Deduplicator

+0

我可以使用只有 – giorgioW

+2

這實際上是一個不平凡的任務,因此對於StackOverflow問題來說過於寬泛。相關論文是:* Guy L. Steele,Jon L. White:「如何準確地打印浮點數字」。 ACM SIGPLAN公告,第25卷第6期,1990年6月,第112-126頁*以及* Robert G. Burger,R. Kent Dybvig:「快速準確地打印浮點數」。在Proc。 ACM SIGPLAN '96關於程序設計語言設計和實現會議,1996年,第108-116頁。* – njuffa

回答

2

相信正在執行該操作的以下你描述:

我使用int作爲中間表示,因爲它具有相同數目的比特作爲浮子(我的機器上),並且它允許從容易轉換二進制字符串。

#include <stdio.h> 

union { 
    int i; 
    float f; 
} myunion; 

int binstr2int(char *s) 
{ 
    int rc; 
    for (rc = 0; '\0' != *s; s++) { 
     if ('1' == *s) { 
      rc = (rc * 2) + 1; 
     } else if ('0' == *s) { 
      rc *= 2; 
     } 
    } 
    return rc; 
} 

int main(void) { 

    // the input binary string (4 bytes) 
    char * input = "11000000110110011001100110011010"; 
    float *output; 


    // convert to int, sizeof(int) == sizeof(float) == 4 
    int converted = binstr2int(input); 

    // strat 1: point memory of float at the int 
    output = (float*)&converted; // cast to suppress warning 
    printf("%f\n", *output); // -6.8 

    // strat 2: use a union to share memory 
    myunion.i = converted; 
    printf("%f\n", myunion.f); // -6.8 

    return 0; 
} 

由於@DanielKamilKozar指出,正確的類型爲intuint32_t。但是,這將需要包括<stdint.h>

+0

「int」不一定與「float」具有相同的位數。一個'uint32_t'呢。 –

+0

@DanielKamilKozar你是對的,我已經添加了一個註釋。只是試圖保持在只包括'' – thelaws

+0

@DanielKamilKozar的要求:如果我們去迂腐,讓我們去整個豬:不能保證'浮動'是IEE754單一presicion浮點。雖然我猜我們可以認爲這是問題的先決條件...... – Deduplicator

相關問題