Skip to content

Commit

Permalink
Added bitcast function to APMath
Browse files Browse the repository at this point in the history
  • Loading branch information
chrysante committed Apr 2, 2023
1 parent 2ab6e36 commit e811b2f
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
32 changes: 32 additions & 0 deletions include/APMath/Conversion.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#ifndef APMATH_CONVERSION_H_
#define APMATH_CONVERSION_H_

#include <climits>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <utility>

namespace APMath {

class APInt;
class APFloat;

/// Convert value \p from to the value of type `To` with the same bit representation as \p from
template <typename To, typename From>
To bitcast(From const& from); // Undefined

template <>
APInt bitcast(APFloat const& from);

template <>
APFloat bitcast(APInt const& from);

} // namespace APMath

#endif // APMATH_CONVERSION_H_
31 changes: 31 additions & 0 deletions src/Conversion.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <APMath/Conversion.h>

#include <cassert>
#include <bit>

#include <APMath/APInt.h>
#include <APMath/APFloat.h>

using namespace APMath;

template <>
APInt APMath::bitcast(APFloat const& from) {
if (from.precision() == APFloatPrec::Single) {
return APInt(std::bit_cast<uint32_t>(from.to<float>()), 32);
}
else {
return APInt(std::bit_cast<uint64_t>(from.to<double>()), 64);
}
}

template <>
APFloat APMath::bitcast(APInt const& from) {
assert((from.bitwidth() == 32 || from.bitwidth() == 64) &&
"Other sizes are not supported by APFloat");
if (from.bitwidth() == 32) {
return APFloat(std::bit_cast<float>(from.to<uint32_t>()), APFloatPrec::Single);
}
else {
return APFloat(std::bit_cast<double>(from.to<uint64_t>()), APFloatPrec::Double);
}
}

0 comments on commit e811b2f

Please sign in to comment.