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.

Revisions

  1. sfc9982 revised this gist Aug 17, 2023. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion float_bitwise.cpp
    Original file line number Diff line number Diff line change
    @@ -45,7 +45,7 @@ auto main() -> int {
    print(c_dynamic_cast, d1);
    std::cout << "cpp_static_cast:" << '\n';
    print(cpp_static_cast, d1);
    std::cout << "Succedded Situation:" << '\n';
    std::cout << "Succeeded Situation:" << '\n';
    std::cout << "reinterprete_cast:" << '\n';
    print(reinterprete_cast_fabs, d1);
    std::cout << "ptr_cast_fabs:" << '\n';
  2. sfc9982 created this gist Jan 12, 2023.
    58 changes: 58 additions & 0 deletions float_bitwise.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    #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 << "Succedded 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;
    }