Re: [問題] float 轉 bit串

看板C_and_CPP作者 (艾斯寇德)時間16年前 (2008/07/30 21:50), 編輯推噓4(404)
留言8則, 4人參與, 最新討論串2/3 (看更多)
※ 引述《Cheese27 (チーズ)》之銘言: : 有個小問題想請教各位 : 就是一般實數 (int long float double)和其bit串(string) : 互相轉換的方法 : 整數很好處理但是float和double : 就有點遇到問題 : 不知道怎麼知道float和double要怎麼知道他的bit串表示方式 : 不知道有沒有好用的C或C++ function可以用 : 謝謝大家!! 可以利用struct的bit field,排好格式 並將變數跟union放在一起,使之位於同一個記憶體上。 typedef union { struct { long sign :1; long exponent :8; long mantissa :23; }float_struct; float value; }float_union; typedef union { struct { long sign :1; long exponent :11; long mantissa_hi : 32; long mantissa_low : 20; }double_struct; double value; }double_union; 之後再依照需求印出就是了。 void show_double_struct(double d) { double_union u; u.value = d; printf("Sign: %1x\n",u.double_struct.sign); printf("Exponent: %03x\n",u.double_struct.exponent); printf("Mantissa: %08x%-5x\n\n", u.double_struct.mantissa_hi, u.double_struct.mantissa_low); } void show_float_struct(float f) { float_union u; u.value = f; printf("Sign: %1x\n",u.float_struct.sign); printf("Exponent: %02x\n",u.float_struct.exponent); printf("Mantissa: %06x\n",u.float_struct.mantissa); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.227.230.228 ※ 編輯: sunneo 來自: 61.227.230.228 (07/30 21:52)

07/30 22:00, , 1F
至於為什麼是那樣的格式,就找找IEEE754 floating point
07/30 22:00, 1F

07/30 22:31, , 2F
bitset不行嗎?@@
07/30 22:31, 2F

07/30 22:35, , 3F
不錯阿 我也會這樣寫~ 缺點是Big-Endian和Little-Endian
07/30 22:35, 3F

07/30 22:47, , 4F
感謝sunneo大的解答!!
07/30 22:47, 4F

07/30 22:48, , 5F
可以再請教一下 long sign :1;中的":1"的宣告代表什麼嗎?
07/30 22:48, 5F

07/30 22:49, , 6F
bit field,代表他佔用1bit
07/30 22:49, 6F

07/30 22:54, , 7F
喔喔 了解了 再次感謝~
07/30 22:54, 7F

08/14 15:50, , 8F
確實會有big-endian以及little endian問題 :(
08/14 15:50, 8F
文章代碼(AID): #18a76uYH (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #18a76uYH (C_and_CPP)