Skip to content

Instantly share code, notes, and snippets.

@sfc9982
Last active August 17, 2023 07:29
Show Gist options
  • Save sfc9982/cdce70dea50ee580d94ed96f4ddb7ebc to your computer and use it in GitHub Desktop.
Save sfc9982/cdce70dea50ee580d94ed96f4ddb7ebc to your computer and use it in GitHub Desktop.
Absolute value of a double in C++23
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iomanip>
#include <iostream>
constexpr uint64_t mask = 0x7fffffffffffffff;
constexpr double d1 = -3.1415926;
void print(double (&func)(double), double x) {
// std::cout << "-----------------------" << std::endl;
std::cout << std::fixed << std::setprecision(8) << func(x) << std::endl;
std::cout << "-----------------------" << std::endl;
}
double c_dynamic_cast(double x) {
return (double) (((uint64_t) x) & mask);
}
double cpp_static_cast(double x) {
return static_cast<double>(static_cast<uint64_t>(x) & mask);
}
double ptr_cast_fabs(double x) {
return *(double *) (*(uint64_t *) (&x) &= mask, &x);
}
double reinterprete_cast_fabs(double x) {
return *reinterpret_cast<double *>(*reinterpret_cast<uint64_t *>(&x) &= mask, &x);
}
double type_pun_fabs(double x) {
union {
uint64_t i;
double d;
} u;
u.d = x;
u.i &= mask;
return u.d;
}
auto main() -> int {
std::cout << "Failed Situation: data loss and complement format dislay" << '\n';
std::cout << "c_dynamic_cast:" << '\n';
print(c_dynamic_cast, d1);
std::cout << "cpp_static_cast:" << '\n';
print(cpp_static_cast, d1);
std::cout << "Succeeded Situation:" << '\n';
std::cout << "reinterprete_cast:" << '\n';
print(reinterprete_cast_fabs, d1);
std::cout << "ptr_cast_fabs:" << '\n';
print(ptr_cast_fabs, d1);
std::cout << "type_pun_fabs:" << '\n';
print(type_pun_fabs, d1);
std::cout << "fabs:" << '\n';
print(fabs, d1);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment