加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C++ 16位浮点数 (转载)

(2015-06-12 09:33:59)
分类: c/c++技巧
Source Code:
  • Float16.h
#ifndef FLOAT16_H
#define FLOAT16_H


class Float16
{
    public:
        inline Float16(void) : raw(0U) {}
        Float16(const Float16&);
        Float16(const float);
        Float16(const unsigned short);
        Float16(const unsigned char, const unsigned char);
        virtual inline ~Float16(void) {}

        void setFloat(const float);
        void setUShort(const unsigned short);
        Float16& operator=(const Float16&);
        Float16& operator=(const float);
        Float16& operator=(const unsigned short);

        float floatValue(void) const;
        unsigned short ushortValue(void) const;
        int getSign(void) const;
        int getExponent(void) const;
        int getFraction(void) const;
    private:
        unsigned short raw;
};

#endif // FLOAT16_H
  • Float16.cpp
#include "Float16.h"

Float16::Float16(const Float16& f16)
{
    this->raw = f16.raw;
}

Float16::Float16(const float f)
{
    this->setFloat(f);
}

Float16::Float16(const unsigned short us)
{
    this->raw = us;
}

Float16::Float16(const unsigned char h, const unsigned char l)
{
    this->raw = h << 8 | l;
}

void Float16::setFloat(const float f)
{
    unsigned int* ui = (unsigned int*)&f;
    this->raw = ((*ui) >> 16) & 0x8000;
    this->raw |= (((((*ui) >> 23) & 0xff) - 0x70) << 10);
    this->raw |= (((*ui) >> 13) & 0x3ff);
}

void Float16::setUShort(const unsigned short us)
{
    this->raw = us;
}

Float16& Float16::operator=(const Float16& f16)
{
    this->raw = f16.raw;
    return *this;
}

Float16& Float16::operator=(const float f)
{
    this->setFloat(f);
    return *this;
}

Float16& Float16::operator=(const unsigned short us)
{
    this->raw = us;
    return *this;
}

float Float16::floatValue(void) const
{
    union {
        float f;
        unsigned int i;
    } v;
    v.i = (this->raw & 0x8000) << 16;
    v.i |= ((((this->raw >> 10) & 0x1f) + 0x70) << 23);
    v.i |= ((this->raw & 0x3ff) << 13);
    return v.f;
}

unsigned short Float16::ushortValue(void) const
{
    return this->raw;
}

int Float16::getSign(void) const
{
    return this->raw >> 15;
}

int Float16::getExponent(void) const
{
    return (this->raw >> 10) & 0x1f;
}

int Float16::getFraction(void) const
{
    return this->raw & 0x3ff;
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有