Skip to content

Instantly share code, notes, and snippets.

@airglow923
Last active October 30, 2021 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airglow923/9d6f786185c3ebb8dc68459b9cefa921 to your computer and use it in GitHub Desktop.
Save airglow923/9d6f786185c3ebb8dc68459b9cefa921 to your computer and use it in GitHub Desktop.
Floating-point number to binary in C++
#include <concepts> // integral
#include <cstddef> // size_t
#include <iostream> // cout
#include <ranges> // iota, reverse
namespace {
constexpr auto
is_bit_set(long long i, std::size_t n) -> bool {
return (i & (1LL << n)) != 0;
}
template <std::integral I, std::size_t N = sizeof(I) << 3>
auto
print_bits(I i) -> void {
for (auto &&n : std::views::iota(0U, N) | std::views::reverse) {
std::cout << is_bit_set(i, n);
}
std::cout << '\n';
}
} // namespace
auto
main() -> int {
static_assert(sizeof(float) == sizeof(int));
static_assert(sizeof(double) == sizeof(long));
union {
double d;
long l;
} a = {.d = 1234 / 2.0}, b = {.d = 1234 / 10.0};
print_bits(a.l);
print_bits(b.l);
}
#include <bitset> // bitset
#include <climits> // CHAR_BIT
#include <concepts> // floating_point
#include <cstddef> // size_t
#include <iostream> // cout
#include <type_traits> // conditional
namespace {
template <std::floating_point F, std::size_t BYTES = sizeof(F),
typename I = std::conditional_t<BYTES == sizeof(int), int, long>>
constexpr auto
get_floating_point_binary(F f) -> std::bitset<BYTES * CHAR_BIT> {
union {
F f;
I i;
} bits = {.f = f};
return bits.i;
}
} // namespace
auto
main() -> int {
static_assert(sizeof(float) == sizeof(int));
static_assert(sizeof(double) == sizeof(long));
auto two = get_floating_point_binary(1234 / 2.0);
auto ten = get_floating_point_binary(1234 / 10.0);
std::cout << two << '\n' << ten << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment