2

As far as I know, all 'traditional' ways of doing this, namely reinterpret_cast of a pointer and union with int and float fields are UB as violation of strict aliasing (in C++, not in C).
So, how to do it correctly without undefined behavior?

Can I do a reinterpret_cast to char * and memcpy that to uint32_t? Or maybestd::launder will help?

Amomum
  • 6,217
  • 8
  • 34
  • 62
  • If all you want to do is “get” the bit representation, you can simply convert a pointer to the `float` to `const unsigned char *` and use the resulting pointer to examine the bytes of the object. But why do you mention “memcpy that to float”? Copying to a `float` is not getting the bit representation; it is changing the bits. What do you really want to do? – Eric Postpischil Oct 13 '19 at 20:06
  • 2
    There was an [1h talk](https://www.youtube.com/watch?v=_qzMpk-22cc) about this problem on cppcon 2019. You might be interested in it. – Timo Oct 13 '19 at 20:06
  • @EricPostpischil yeah, sorry, I meant 'memcpy to uint32_t`, I'll edit the question. – Amomum Oct 13 '19 at 20:07
  • `memcpy that to uint32_t` - why would you do that to print bits? You can print them from `char`. – KamilCuk Oct 13 '19 at 20:08
  • @KamilCuk well, I want to have them as a single continuous thingy, to get significand and exponent; getting them from char array will be a bit tedious. – Amomum Oct 13 '19 at 20:11

1 Answers1

2

The standard way to do it, as pointed out by Jason Turner, is to use memcpy:

float f = 1.0;
std::byte c[sizeof(f)];
memcpy(c, &f, sizeof(f));

You may be thinking that you do not want to copy anything, that you just want to see the bits/bytes. Well the compilers are smart and they will in fact optimize it away as demonstrated by Jason so do not worry and use memcpy for this kind of thing and never reinterpret_cast.

Resurrection
  • 3,916
  • 2
  • 34
  • 56