取得float的bit表示法。
1.evil union

union Foo {
unsigned u;
float f;
};

2.pointer casting

unsigned* pu = (unsigned*) &f;

3.memcpy(&u, &f, sizeof(u));
以上只能用於Primitive types,對於compound types不可假定其memory layout。
然後就可以印出個別成分

void PrintBits(unsigned u, unsigned msb=1<<31, unsigned lsb=1) {
for ( ; msb >= lsb; msb >>= 1) printf("%d", (msb&u)>0);
}
PrintBits(u, 1<<31, 1<<31);  //sign bit
PrintBits(u, 1<<30, 1<<23);  //exp
PrintBits(u, 1<<22);         //fraction

不用上述方法,<math.h>也提供了幾個函數

float frexpf(float value, int *exp);
double frexp(double value, int* exp );

(舊blog文章改寫)


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 novus 的頭像
    novus

    novus log

    novus 發表在 痞客邦 留言(0) 人氣()