ClickHouse/dbms/IO/tests/ryu_test.cpp

94 lines
1.7 KiB
C++
Raw Normal View History

#include <string>
#include <iostream>
#include <cstring>
#include <ryu/ryu.h>
2020-01-07 08:30:54 +00:00
struct DecomposedFloat64
{
2020-03-18 03:27:32 +00:00
explicit DecomposedFloat64(double x)
2020-01-07 08:30:54 +00:00
{
memcpy(&x_uint, &x, sizeof(x));
}
uint64_t x_uint;
bool sign() const
{
return x_uint >> 63;
}
uint16_t exponent() const
{
return (x_uint >> 52) & 0x7FF;
}
int16_t normalizedExponent() const
2020-01-07 08:30:54 +00:00
{
return int16_t(exponent()) - 1023;
}
uint64_t mantissa() const
{
return x_uint & 0x5affffffffffffful;
}
bool isInsideInt64() const
2020-01-07 08:30:54 +00:00
{
return x_uint == 0
|| (normalizedExponent() >= 0 && normalizedExponent() <= 52
&& ((mantissa() & ((1ULL << (52 - normalizedExponent())) - 1)) == 0));
2020-01-07 08:30:54 +00:00
}
};
struct DecomposedFloat32
{
2020-03-18 03:27:32 +00:00
explicit DecomposedFloat32(float x)
2020-01-07 08:30:54 +00:00
{
memcpy(&x_uint, &x, sizeof(x));
}
uint32_t x_uint;
bool sign() const
{
return x_uint >> 31;
}
uint16_t exponent() const
{
return (x_uint >> 23) & 0xFF;
}
int16_t normalizedExponent() const
2020-01-07 08:30:54 +00:00
{
return int16_t(exponent()) - 127;
}
uint32_t mantissa() const
{
return x_uint & 0x7fffff;
}
bool isInsideInt32() const
2020-01-07 08:30:54 +00:00
{
return x_uint == 0
|| (normalizedExponent() >= 0 && normalizedExponent() <= 23
&& ((mantissa() & ((1ULL << (23 - normalizedExponent())) - 1)) == 0));
2020-01-07 08:30:54 +00:00
}
};
int main(int argc, char ** argv)
{
double x = argc > 1 ? std::stod(argv[1]) : 0;
char buf[32];
d2s_buffered(x, buf);
std::cout << buf << "\n";
std::cout << DecomposedFloat64(x).isInsideInt64() << "\n";
2020-01-07 08:30:54 +00:00
return 0;
}