我正在尋找將浮點數轉換爲C語言的十進制表示法的最佳方法。我將嘗試給出一個例子:用戶在IEEE754中引入一個數字(1 1111111 10101 ...),程序必須返回十進制表示(例如25.6)
我嘗試過使用掩碼和按位運算,但是我沒有得到任何邏輯結果。IEEE 754到C語言的十進制數
回答
相信正在執行該操作的以下你描述:
我使用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指出,正確的類型爲int
是uint32_t
。但是,這將需要包括<stdint.h>
。
「int」不一定與「float」具有相同的位數。一個'uint32_t'呢。 –
@DanielKamilKozar你是對的,我已經添加了一個註釋。只是試圖保持在只包括'
@DanielKamilKozar的要求:如果我們去迂腐,讓我們去整個豬:不能保證'浮動'是IEE754單一presicion浮點。雖然我猜我們可以認爲這是問題的先決條件...... – Deduplicator
- 1. Java浮點到IEEE-754十六進制?
- 2. 將十六進制轉換爲IEEE 754
- 3. 從IEEE-754轉換爲十進制
- 4. 在C#中將十六進制轉換爲IEEE 754浮點數
- 5. 十六進制浮點數IEEE 754雙精度C++
- 6. 轉換十進制到單精度IEEE 754
- 7. 將十六進制字符串轉換爲IEEE 754浮點數
- 8. 轉換IEEE 754浮點數以十六進制字符串
- 9. IEEE 754-2008的可用實現(密集十進制)
- 10. 將十進制轉換爲IEEE-754格式
- 11. Ruby將64位IEEE 754十六進制轉換爲雙精度
- 12. IEEE十進制到二進制轉換
- 13. C程序設計IEEE 754小數二進制轉換器
- 14. 如何將十六進制轉換爲IEEE 754 32位浮點C++
- 15. matlab中的32位十六進制到32位浮點(IEEE 754)轉換
- 16. 在Java中獲得(十進制)浮點數的IEEE 754(單精度)表示法
- 17. IEEE 754:Java腳本對C
- 18. Java - 將十六進制轉換爲IEEE-754 64位浮點數 - 雙精度
- 19. IEEE 754中的指數
- 20. IEEE-754浮點數舍入機制
- 21. 將IEEE-754雙精度和單精度轉換爲十進制Java bug
- 22. 什麼是IEEE-754?
- 23. 將二進制32位IEEE-754浮點數轉換爲.net
- 24. 不正確指數(?)從十進制表示轉換浮子32位二進制(IEEE 754浮點)時
- 25. C語言,運行失敗,十進制爲二進制
- 26. C#IEEE754到十進制
- 27. 使用IEEE 754將浮點數轉換爲基數10使用IEEE 754
- 28. C語言中十進制數的錯誤計算
- 29. 如何交換c語言中的十六進制數字?
- 30. 從MIPS C到Java轉換的IEEE 754雙精度數字
爲什麼不使用標準庫函數? – Deduplicator
我可以使用只有 –
giorgioW
這實際上是一個不平凡的任務,因此對於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