C++ 16位浮点数 (转载)
(2015-06-12 09:33:59)分类: c/c++技巧 |
Source Code:
#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::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;
}
- Float16.h
#define FLOAT16_H
class Float16
{
};
#endif // FLOAT16_H
- Float16.cpp
Float16::Float16(const Float16& f16)
{
}
Float16::Float16(const float f)
{
}
Float16::Float16(const unsigned short us)
{
}
Float16::Float16(const unsigned char h, const unsigned char l)
{
}
void Float16::setFloat(const float f)
{
}
void Float16::setUShort(const unsigned short us)
{
}
Float16& Float16::operator=(const Float16& f16)
{
}
Float16& Float16::operator=(const float f)
{
}
Float16& Float16::operator=(const unsigned short us)
{
}
float Float16::floatValue(void) const
{
}
unsigned short Float16::ushortValue(void) const
{
}
int Float16::getSign(void) const
{
}
int Float16::getExponent(void) const
{
}
int Float16::getFraction(void) const
{
}