作者sunneo (艾斯寇德)
看板C_and_CPP
标题Re: [问题] float 转 bit串
时间Wed Jul 30 21:50:45 2008
※ 引述《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)
1F:→ sunneo:至於为什麽是那样的格式,就找找IEEE754 floating point 07/30 22:00
2F:推 whenyouregon:bitset不行吗?@@ 07/30 22:31
3F:推 netsphere:不错阿 我也会这样写~ 缺点是Big-Endian和Little-Endian 07/30 22:35
4F:推 Cheese27:感谢sunneo大的解答!! 07/30 22:47
5F:→ Cheese27:可以再请教一下 long sign :1;中的":1"的宣告代表什麽吗? 07/30 22:48
6F:→ sunneo:bit field,代表他占用1bit 07/30 22:49
7F:推 Cheese27:喔喔 了解了 再次感谢~ 07/30 22:54
8F:→ sunneo:确实会有big-endian以及little endian问题 :( 08/14 15:50