forked from changkun/modern-cpp-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9.5.type.punning.cpp
More file actions
34 lines (28 loc) · 1016 Bytes
/
Copy path9.5.type.punning.cpp
File metadata and controls
34 lines (28 loc) · 1016 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//
// 9.5.type.punning.cpp
// chapter 09 others
// modern c++ tutorial
//
// created by changkun at changkun.de
// https://github.com/changkun/modern-cpp-tutorial
//
#include <bit>
#include <cstdint>
#include <cstring>
#include <iostream>
int main() {
float f = 3.14f;
// Reinterpreting an object's bytes via a different type through a
// pointer/reference cast violates the strict-aliasing rule and is
// undefined behavior:
// std::uint32_t bad = *reinterpret_cast<std::uint32_t*>(&f); // UB
// Portable and always-valid approach (any standard): std::memcpy.
std::uint32_t bits;
std::memcpy(&bits, &f, sizeof bits);
// C++20: std::bit_cast does the same well-defined reinterpretation
// and is usable in constant expressions.
auto bits2 = std::bit_cast<std::uint32_t>(f);
std::cout << std::hex << bits << " == " << bits2 << std::dec
<< " : " << (bits == bits2) << "\n";
std::cout << "round-trip: " << std::bit_cast<float>(bits2) << "\n";
}