作者MOONRAKER (㊣科学小飞侠8号又笨又秃)
看板C_and_CPP
标题Re: [问题] float 转 bit串
时间Wed Jul 30 22:38:44 2008
※ 引述《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!
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ https://www.youtube.com/user/JamesBondXD▄▄
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.115.198.97
1F:推 sunneo:太棒了 以前的文章还是很值得推. 07/30 22:48
2F:→ MOONRAKER:老大比较厉害 我一直很狐疑union这东西存在是要干嘛的 07/31 13:45
3F:→ MOONRAKER:这下终於找到它实际的用途 XD 07/31 13:45
4F:推 cplusplus:用途很多啊 上网search一下.... 07/31 14:27