您的位置:首页 > 其它

用位域描述float和double值

2015-11-28 18:34 197 查看
/// @file exam_1_1.cpp
/// @brief 用位域描述float和double值

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <crtdbg.h>
#include <conio.h>

typedef struct _tag_bits_struct_float
{
    unsigned int data : 23;
    unsigned int exp : 8;
    unsigned int sign : 1;
}TAG_BITS_STRUCT_FLOAT;

typedef struct _tag_bits_struct_double
{
    /// 位域字段长度超过32Bits后, 必须要分成多段
    /// data is 52
    unsigned int dataL : 32;
    unsigned int dataH : 20;

    unsigned int exp : 11;
    unsigned int sign : 1;
}TAG_BITS_STRUCT_DOUBLE;

void fnUseBitsStructShowFloat(float fIn);
void fnUseBitsStructShowDouble(double dblIn);

int main(int argc, char *argv[ ], char *envp[ ])
{
    fnUseBitsStructShowFloat(3.75f);
    fnUseBitsStructShowDouble(3.75);
    
    printf("END, press any key to quit\n");
    getchar();
    
    return 0;
}

void fnUseBitsStructShowFloat(float fIn)
{
    TAG_BITS_STRUCT_FLOAT* pBitStructFloat = (TAG_BITS_STRUCT_FLOAT*)&fIn;

    // 00 00 70 40 => low addr to high addr
    /**
    pBitStructFloat->sign  = 0x0
    pBitStructFloat->exp  = 0x80
    pBitStructFloat->data = 0x700000
    */

    printf("pBitStructFloat->sign  = 0x%.1x\n"
            "pBitStructFloat->exp  = 0x%.2x\n"
            "pBitStructFloat->data = 0x%.3x\n", 
        pBitStructFloat->sign,
        pBitStructFloat->exp,
        pBitStructFloat->data);
}

void fnUseBitsStructShowDouble(double dblIn)
{
    TAG_BITS_STRUCT_DOUBLE* pBitStructDouble = (TAG_BITS_STRUCT_DOUBLE*)&dblIn;

    // 00 00 00 00 00 00 0E 40
    
    /**
    S = 0
    double的E = 1023 + N
    E = 1 + 1023 = 1024 = 10000000000B
    D = 1110B = 1110 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000B
    */

    /**
    pBitStructDouble->sign  = 0x0
    pBitStructDouble->exp  = 0x400
    pBitStructDouble->dataH = 0xe0000
    pBitStructDouble->dataL = 0x0
    */

    printf("pBitStructDouble->sign  = 0x%x\n"
            "pBitStructDouble->exp  = 0x%x\n"
            "pBitStructDouble->dataH = 0x%x\n" 
            "pBitStructDouble->dataL = 0x%x\n", 
        pBitStructDouble->sign,
        pBitStructDouble->exp,
        pBitStructDouble->dataH,
        pBitStructDouble->dataL);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: