大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
#include "stdafx.h"
#include 
<iostream>

using namespace std;

//    float 1.5  二进制表示如下
//    0                01111111            10000000000000000000000
//    符号位(1 bit)    指数位(8 bits)    有效数位(23 bits)
//    2^(指数位-(2^8/2-1)) = 1            有效位的二进制表示:1.1(整数部分的1为隐藏,有效数位为2进制的小数部分)  (dec)=1.5

//    double
//    符号位(1 bit)    指数位(11 bits)    有效数位(52 bits)

void OutBinary(float f)        //Output the float in binary object format
{
    cout
<<"float: "<<f<<endl;
    
int i = 0;
    memcpy(
&i, &f, 4);
    cout
<<"int: "<<i<<endl;
    
char cDest[33= {0};
    
char c[33= {0};
    itoa(i, c, 
2);
    
int iNum = 0;
    
char* cIterator = c;
    
while(*cIterator != '\0'{
        
++cIterator;
        
++iNum;
    }

    
int iIterator = 32;
    
for(int iCnt=iNum; iCnt>0--iCnt) {
        cDest[iIterator
-1= c[iCnt-1];
        
--iIterator;
    }
 
    
while(iIterator>0{
        
--iIterator;
        cDest[iIterator] 
= '0';
    }

    printf(
"%c ", cDest[0]);
    
for(int iCnt=1; iCnt<9++iCnt) {
        printf(
"%c", cDest[iCnt]);
    }

    printf(
" ");
    
for(int iCnt=9; iCnt<32++iCnt) {
        printf(
"%c", cDest[iCnt]);
    }

    cout
<<endl;
}


int main()
{
    
float f = 1.5;            //    0                01111111            10000000000000000000000
    OutBinary(f);
    OutBinary(
0);            //    0                00000000            00000000000000000000000
    OutBinary(1);            //    0                01111111            00000000000000000000000
    unsigned int q = 0;
    memcpy(
&q, &f, 4);
    q 
|= 1<<31;
    memcpy(
&f, &q, 4);
    OutBinary(f);
    
return 0;
}

posted on 2009-06-29 10:38 大胖 阅读(421) 评论(0)  编辑 收藏 引用 所属分类: Others

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理