Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4842835
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: C/C++

2009-07-01 08:57:15

#include <stdint.h>

uint32_t htonf(float f)
{
    uint32_t p;
    uint32_t sign;

    if (f < 0) { sign = 1; f = -f; }
    else { sign = 0; }
        
    p = ((((uint32_t)f)&0x7fff)<<16) | (sign<<31); // whole part and sign

    p |= (uint32_t)(((f - (int)f) * 65536.0f))&0xffff; // fraction


    return p;
}

float ntohf(uint32_t p)
{
    float f = ((p>>16)&0x7fff); // whole part

    f += (p&0xffff) / 65536.0f; // fraction


    if (((p>>31)&0x1) == 0x1) { f = -f; } // sign bit set


    return f;
}



The above code is sort of a naive implementation that stores a float in a 32-bit number. The high bit (31) is used to store the sign of the number ("1" means negative), and the next seven bits (30-16) are used to store the whole number portion of the float. Finally, the remaining bits (15-0) are used to store the fractional portion of the number.
阅读(2560) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~