Re: [問題] float 轉 bit串

看板C_and_CPP作者 (㊣科學小飛俠8號又笨又禿)時間16年前 (2008/07/30 22:38), 編輯推噓2(202)
留言4則, 3人參與, 最新討論串3/3 (看更多)
※ 引述《Cheese27 (チーズ)》之銘言: : 有個小問題想請教各位 : 就是一般實數 (int long float double)和其bit串(string) : 互相轉換的方法 : 整數很好處理但是float和double : 就有點遇到問題 : 不知道怎麼知道float和double要怎麼知道他的bit串表示方式 : 不知道有沒有好用的C或C++ function可以用 : 謝謝大家!! 可以用指標傳入副程式, 副程式用void *接,強迫轉型為int,再用bitmask得到各個bit。 因為發現當初paste的code很快就被該站丟掉了 在這裡重貼一次 http://nopaste.org/p/aH9ASi4hl 也一併附在下面 使用效果請參考拙作 #17uX-3Vi // fdemo: a program that demonstrates internal representation of C float // and ought to be completed LONG LONG LONG LONG LONG LONG ago // // MOONRAKER // 20 Mar 2008 #include <cstdio> #include <cstdlib> using namespace std; void manifest(void *n) { unsigned int repres = *((int *) n); float value = *((float *) n); unsigned int signs, exponent, mantissa; printf ("%10f : %08x : ", value, repres); signs = (repres & 0x80000000) >> 31; exponent = (repres & 0x7f800000) >> 23; mantissa = (repres & 0x007fffff); for (int i=31; i>=0; --i) { printf( ((1<<i) & repres) ? "1" : "0" ); if (i==31) printf (" "); if (i==23) printf ("/%02x(%+4d) ", exponent, exponent-127); if (i==0) printf ("/%06x ", mantissa); } printf("\n"); } main(int argc, char **argv) { if (argc<=1) { printf("usage: fdemo <floatnum> [ <floatnum2> ... <floatnumN> ]\n"); exit(1); } // And now argc surely larger than 1 for (int i=1; i<argc; ++i) { float n=strtod(argv[i], NULL); manifest(&n); } return 0; } // End of program (fdemo.cpp)   -- BATCH 03 : 買張床 - 切達大俠 - 伐木人之歌 - http://tinyurl.com/3zpyx5 [B4準備中]: 謳歌金錢(7/02) - 單車超人(7/23) - http://tinyurl.com/66v6vq [ 番外篇 ]: 包租婆也有過當羅莉的時候(7/17) - http://tinyurl.com/6j4ale ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ 蒙帝派松正體中文計畫 Spam-a-lot and enjoy the pythonesque delight! ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ http://www.youtube.com/user/JamesBondXD▄▄ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.115.198.97

07/30 22:48, , 1F
太棒了 以前的文章還是很值得推.
07/30 22:48, 1F

07/31 13:45, , 2F
老大比較厲害 我一直很狐疑union這東西存在是要幹嘛的
07/31 13:45, 2F

07/31 13:45, , 3F
這下終於找到它實際的用途 XD
07/31 13:45, 3F

07/31 14:27, , 4F
用途很多啊 上網search一下....
07/31 14:27, 4F
文章代碼(AID): #18a7ptfs (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #18a7ptfs (C_and_CPP)