c語言以及高級語言中的float到底是什么以及IEEE754
對內存里float4字節的好奇
初學計算機都要學那個什么二進制十進制什么補碼 反碼那些玩意兒哈,由于最近要做一個單片機往另外一個單片機發數據的需求,直接c語言指針 然后float4字節傳過去不就得了嗎,麻煩就麻煩在這里 另一端編程機是個啥鳥lua 麻煩的一逼,integer這種我們就不說了哈因為實在是太直白了沒啥技術含量,我們今天來啃float這個硬骨頭。你知不知道什么叫ieee754 。float到底可表示的范圍是多少到多少。以前聽過一個老手講的課 ,說實話這玩意兒編程多年的老手 說的都模棱兩可。當我啃著感覺稍微有點硬了 又不斷的查資料 探索。我知道我又得寫一篇博文以做記錄了。還好不算很硬。沒經過多少搗鼓就出來了。c#這玩意兒 用著還真是順滑,當然純c嵌入式我也干了一年多了 對這種“低級語言”以及計算機底層又有了稍微深刻一點的認識了。這么多年了c#用順手了 習慣用它做基礎算法和邏輯驗證 ,然后移植為其它語言的。

關于ieee754的資料網上大把的 你就隨便搜一篇吧 比如這:
https://blog.csdn.net/MaTF_/article/details/124842807
在線測試工具:
https://www.h-schmidt.net/FloatConverter/IEEE754.html
我們也是看了后 照著原理用代碼實現的。
有沒有想過c語言以及其他高級語言里編程基礎里的float數據類型的4個字節在計算機里到底是怎么轉換顯示在你屏幕上的 是不是有時候我們從來沒想過一個東西是怎么來的。float是4字節的,那么我們給一串4字節。如果是c#你還不知道有bitconverter這個函數怎么辦?
我自己參考然后成功實現了過后的一些理解
看 整體概覽中心思想 還是跟我們十進制一樣的 底數+指數的形式 第一個有效數字肯定是1 開始的 所以最前面一位去掉(解析的時候默認它是有的)比如 1x10^3 這種形式。只不過我們這里的 指數和底數 都是二進制。小數部分 代碼處理 為什么是負的次方 ,稍微停頓下 11.01 二進制還有小數這個比較費解,那么通行于二進制整數的規則 進位則x2 ,那么小數部分則是往后一位則/2 想想我們十進制數 2的負2次方 就是 1/(2x2) 就是四分之一 是不是啊 。那么我們這里也是同樣的道理。
指數部分 ,這里也是二進制的指數 不是10進制的 ,這里有8位 那么 就是 底數部分可以x2^-127 到128 次方 。雖然第一次理解有點別扭 ,稍微梳理下 整體感覺還是比較順暢的。說明計算機科學家還是經過深思熟慮考慮過的。
關于數值精確表示與非精確表示
然后另外一個 ,基于這種原理 機制,活了這么多年 你才發現 這個float有時候 并不能 精確表示一個數 0.125 這種 還好說,為啥能夠精確標識啊,你看他小數點往后完全符合描述的 -2次方 也就是二分機制 ,相信通過上面那些理解 不用我搬那些高深的理論 講解你也能夠明白 從1 分下來 0.5 0.25 0.125 剛好分完。
看一個不能夠精確分完的1567.37 -> 1567.36987304688 看 是不是很神奇的事情出現了 ,這不是bug 就是由于他機制本身的原因所致的。我們不能改變它 就只能與他共存。 就像有理數除某些數除不盡 一樣的 這里也是機制本身決定的 暫且理解為類似的東西吧。
下面是閱讀了上面的參考文獻后經過驗證的代碼成功實現
我代碼里注釋已經寫得相當詳盡了
1 //ieee754 格式float解析 2 public void iee754BytesToVal(byte[] bytes) 3 { 4 //所有的位序列 5 bool[] bits = new bool[32]; 6 7 8 9 //先進行翻轉 10 Array.Reverse(bytes); 11 12 //進行數據預處理 13 int bitarIndx=0; 14 for (int i = 0; i < 8; i++) 15 { 16 bits[bitarIndx++] = (bytes[0] & (0x80>>i))>0?true:false; 17 } 18 19 for (int i = 0; i < 8; i++) 20 { 21 bits[bitarIndx++] = (bytes[1] & (0x80 >> i)) > 0 ? true : false; 22 } 23 24 for (int i = 0; i < 8; i++) 25 { 26 bits[bitarIndx++] = (bytes[2] & (0x80 >> i)) > 0 ? true : false; 27 } 28 29 for (int i = 0; i < 8; i++) 30 { 31 bits[bitarIndx++] = (bytes[3] & (0x80 >> i)) > 0 ? true : false; 32 } 33 34 for (int i = 0; i < bits.Length; i++) 35 { 36 Console.Write(bits[i] == true ? "1" : "0"); 37 Console.Write(" "); 38 } 39 40 41 //獲取某個位 與上 指定的位 42 //獲取符號位 43 int singl = -1; 44 45 if (bits[0]== true) 46 { 47 singl = -1; 48 Console.WriteLine("負數"); 49 } 50 else 51 { 52 singl = 1; 53 Console.WriteLine("正數"); 54 } 55 56 57 //階碼0 1字節 58 //取出對應的階碼位 7f80 59 60 sbyte exponent = 0; 61 for (int i = 0; i < 8; i++) 62 { 63 byte bitSetPoint=0x00; 64 if( bits[1+i]==true) 65 { 66 bitSetPoint = 0x80; 67 } 68 else 69 { 70 bitSetPoint = 0x00; 71 } 72 73 exponent = (sbyte)(exponent | (bitSetPoint >> i)); 74 75 } 76 77 78 //0x7f 79 sbyte exponentID = 0x7f; 80 sbyte exponentReal = (sbyte)(exponent - exponentID); 81 82 83 //尾數 23位 84 double mantissa=0; 85 for (int i = 0; i < 23; i++) 86 { 87 if(bits[9+i]==true) 88 { 89 mantissa = mantissa + Math.Pow(2, -(i + 1)); 90 } 91 else 92 { 93 mantissa = mantissa + 0; 94 } 95 } 96 mantissa = (1 + mantissa) * singl * Math.Pow(2, exponentReal); 97 98 99 Console.WriteLine("最終的數是:" + mantissa); 100 101 }
1 public void iee754ValToBytes(float val) 2 { 3 Console.WriteLine(val.ToString()); 4 string valStr = val.ToString(); 5 6 //符號位 7 int singl = 1; 8 if (valStr.IndexOf('-') != -1) 9 { 10 singl = -1; 11 valStr.Replace("-", ""); 12 } 13 else 14 singl = 1; 15 16 string[] valPartStrs = valStr.Split('.'); 17 18 string frontPartStr = "0"; 19 if (valPartStrs.Length > 0) 20 frontPartStr = valPartStrs[0]; 21 string afterPartStr = "0"; 22 if (valPartStrs.Length > 1) 23 afterPartStr = valPartStrs[1]; 24 25 //整數部分處理 26 List<bool> frontBits = new List<bool>(); 27 int frontNum = int.Parse(frontPartStr); 28 if (frontNum != 0) 29 { 30 31 32 //整數部分 采用短除法 33 long dividend = frontNum; 34 int indx = 0; 35 do 36 { 37 long yu = dividend % 2; 38 dividend /= 2; 39 frontBits.Add(yu == 1 ? true : false); 40 } while (dividend > 0); 41 indx = 0; 42 43 //注意這里有一個反轉 整數部分短除法 和小數部分的x2取整不一樣的 44 frontBits.Reverse(); 45 46 Console.WriteLine("整數部分"); 47 for (int i = 0; i < frontBits.Count; i++) 48 { 49 Console.Write(frontBits[i] == true ? "1" : "0"); 50 Console.Write(" "); 51 } 52 Console.WriteLine(); 53 } 54 55 // 小數部分采用*2取整方法 56 List<bool> afterBits = new List<bool>(); 57 int afterNum = int.Parse(afterPartStr); 58 if (afterNum != 0) 59 { 60 afterPartStr = "0." + afterPartStr; 61 62 63 64 float afterApendOne = float.Parse(afterPartStr); 65 for (int i = 0; i < 23 - frontBits.Count; i++) 66 { 67 68 afterApendOne = afterApendOne * 2; 69 if (Math.Floor(afterApendOne) == 1) 70 afterBits.Add(true); 71 else 72 afterBits.Add(false); 73 string[] tmpxiaoshu = afterApendOne.ToString().Split('.'); 74 if (tmpxiaoshu.Length > 1) 75 { 76 afterApendOne = float.Parse("0." + tmpxiaoshu[1]); 77 if (afterApendOne == 0) 78 break; 79 } 80 else 81 { 82 break; 83 } 84 } 85 86 } 87 //指數部分 88 sbyte exponent = (sbyte)((sbyte)127 + (sbyte)frontBits.Count - 1); 89 90 //總覽數據---------------------------------------------------------------------- 91 List<bool> finalBits = new List<bool>(); 92 //附上符號位 93 94 if (singl > 0) 95 finalBits.Add(false); 96 else 97 finalBits.Add(true); 98 99 100 Console.WriteLine("指數部分"); 101 for (int i = 0; i < 8; i++) 102 { 103 bool exponentBit = (exponent & (0x80 >> i)) > 0 ? true : false; 104 finalBits.Add(exponentBit); 105 106 Console.Write(exponentBit == true ? "1" : "0"); 107 Console.Write(" "); 108 } 109 Console.WriteLine(); 110 111 //附上整數部分 112 for (int i = 1; i < frontBits.Count; i++) 113 { 114 finalBits.Add(frontBits[i]); 115 } 116 117 //附上小數部分 118 for (int i = 0; i < afterBits.Count; i++) 119 { 120 finalBits.Add(afterBits[i]); 121 } 122 123 124 //IEEE754 float 標準 32位 不足的補0 125 Console.WriteLine("---------------------------------"); 126 for (int i = 0; i < finalBits.Count; i++) 127 { 128 Console.Write(finalBits[i] == true ? "1" : "0"); 129 Console.Write(" "); 130 } 131 if (finalBits.Count < 32) 132 { 133 int beaddcount = 32 - finalBits.Count; 134 for (int i = 0; i < (beaddcount); i++) 135 { 136 finalBits.Add(false); 137 Console.Write("0"); 138 Console.Write(" "); 139 } 140 } 141 Console.WriteLine(); 142 Console.WriteLine("---------------------------------"); 143 144 //利用前面的例子進行反向轉換測試 145 146 UInt32 reconvert = 0x00000000; 147 148 149 for (int i = 0; i < 32; i++) 150 { 151 UInt32 bitSetPoint = 0x00000000; 152 if (finalBits[i] == true) 153 { 154 bitSetPoint = 0x80000000; 155 } 156 else 157 { 158 bitSetPoint = 0x00000000; 159 } 160 reconvert = reconvert | (bitSetPoint >> i); 161 } 162 163 byte[] recdata = BitConverter.GetBytes(reconvert); 164 165 Console.WriteLine("-------------開啟再次轉換過程--------------------"); 166 iee754BytesToVal(recdata); 167 }
那么怎么驗證我們的算法是正確的呢,很簡單啊把我們拿出去的float變量轉的bytes 再轉float 結果一致就代表成功了,我們也可以利用c#自帶的BitConverter.GetBytes(float)得到的4字節進行驗證。
1 iee754ValToBytes(1567.37f); 2 //floattobytes(19.625f); 3 return; 4 float f = -7434.34f; 5 byte[] floatar = BitConverter.GetBytes(f); 6 Console.Write("{0:X2}", floatar[0]); 7 Console.Write("{0:X2}", floatar[1]); 8 Console.Write("{0:X2}", floatar[2]); 9 Console.Write("{0:X2}", floatar[3]); 10 Console.WriteLine(); 11 iee754BytesToVal(floatar);
關于代碼的正確性已經毋庸置疑了哈,文章開頭的圖已經給出結果了。
關于通用性
首先所有的編程環境都遵循這個標準 ,不管你c c++ c# java ,c# 里提取的bytes 放到 c++下去解析 是能解析出來的 已經測試過了(都不用解析 就是一個指針內存操作),Java我沒試過相信是一樣的。關于c++的處理 , 看c++指針直接操作內存的優勢和 便利性就出來了。
c語言里獲取的字節碼轉換為float:
1 float channelUpLimit = *(float *)&value[0];
float轉換為字節以相反方式操作就可以了,指針用偽數組操作方式就可以了,你懂的,c語言特別善于玩兒這種內存控制。
編寫代碼時精度問題的陷阱
這又隱申出另外的問題,就是編程語言的數制精度問題。c語言中 float fff = 4796 / 10.0;得到的不是479.6 而是個不知道什么的玩意兒 479.600006 無論用 什么floor這些函數*10+0.5 又/10 處理都相當棘手。網上說用double 可以避免很多問題 ,試了下 用 double fff = 4796 / 10.0; 得到的確實是479.600000
https://www.yisu.com/zixun/371395.html
老早就看到前同事在代碼中寫一些這種玩意兒 ,剛入行不久一臉懵逼 這是什么神經病代碼
1 float a=0, b=0, c=0; 2 if (a - b < 0.00001) 3 c = 0; 4 else 5 c = a - b;
我了個去c語言中都這么麻煩的嗎。2.5 有時候可能并不是2.5 由于計算機底層cpu運算的一些奇奇怪怪的玄機 我們也懶得去管。總之就算2.5 有可能實際是2.49999999999999999999999999
包括javascript 很多都有數制問題。
這段代碼的問題在c# c 中都存在 并且float的標準都是遵循統一的規范 IEEE754 的(c#的二進制在c中解析的結果一樣
1 float test = 0.1f; 2 if (test == (1 - 0.9)) 3 { 4 Console.WriteLine("正常"); 5 } 6 else 7 { 8 Console.WriteLine("what!!!"); 9 }

聰明如你,看了上面的相信你已經知道怎么解決了。c#里更加無腦 傻瓜化的用decimal就可以了。

浙公網安備 33010602011771號