MCPcopy Create free account
hub / github.com/andreasfertig/programming-with-cpp20 / main

Function main

10.01-bitCastFloatToInt0/main.cpp:9–34  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7#include <cstring>
8
9int main()
10{
11 float pi = 3.14f;
12
13 uint32_t a = static_cast<uint32_t>(pi); // #A Does not do what we want
14 // uint32_t b = reinterpret_cast<uint32_t>(pi); // #B Does not compile
15 // #C Uses type-punning, can result in UB
16 uint32_t c = *reinterpret_cast<uint32_t*>(&pi);
17
18 union FloatOrInt {
19 float f;
20 uint32_t i;
21 };
22
23 FloatOrInt u{pi};
24
25 uint32_t d = u.i; // #D A lot of code just for a simple cast
26
27 uint32_t f{};
28 memcpy(&f, &pi, sizeof(f)); // #E Copying the value
29
30 printf("%#x\n", a);
31 printf("%#x\n", c);
32 printf("%#x\n", d);
33 printf("%#x\n", f);
34}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected