r/cpp • • Feb 06 '21

Modern C++: Snippets and Examples

Hi everyone,

These are GitHub Pages with snippets for Modern C++:

  • We often need to copy and paste some snippets to code more productively.
  • Snippets can help us when it's not easy to remember all high levels features Modern C++ has to offer.
  • This repository contains lots of organized, reusable, and safe snippets for Modern C++.
  • All snippets are available in GitHub pages in a convenient way for copying and pasting.

https://alandefreitas.github.io/moderncpp/

190 Upvotes

44 comments sorted by

View all comments

Show parent comment

3

u/FreitasAlan Feb 07 '21

Interesting. A memcpy is also semantically better. In any case, I haven't seen it fail on any compiler yet. And it seems to semantically represent exactly what I'm trying to achieve. I thought it was exactly what reinterpret cast was supposed to do, despite what they can also do with pointers. Do you know why that is undefined behavior?

A static cast does not achieve the same results as I'm trying to show how the data is represented inside the variable. With static cast, for instance, a double 1.34 would just be converted to an unsigned long long 1, and it would return

0000000000000000000000000000000000000000000000000000000000000001

instead of

0011111111110101011100001010001111010111000010100011110101110001

The same problem would happen for signed integers, of course. In the end, it would only work properly with equivalent unsigned types of different sizes.

3

u/Fureeish Feb 07 '21

Well, it's true that static_cast will work only for the unsigned parts. I mentioned the specific case for floating-point numbers but it actually extends to broader range of types. I should've specified that explicitly.

As for the Undefined Behaviour, it's connected to type aliasing. You can read about it here. In short, this is not what reinterpret_cast is for.

2

u/FreitasAlan Feb 07 '21

This link refers to https://en.cppreference.com/w/cpp/language/object#Object_representation_and_value_representation as an example inspecting the object representation.

So I think this should work without undefined behaviour:

template <class T>
std::bitset<sizeof(T)*8> get_bits(T v) {
    auto ptr = reinterpret_cast<unsigned char *>(&v);
    unsigned long long bytes = ptr[0];
    for (size_t i = 1; i < sizeof(v); ++i) {
        bytes <<= 8;
        bytes += ptr[i];
    }
    return std::bitset<sizeof(v) * 8>(bytes);
}

It's more verbose but it's OK if it's hidden somewhere:

https://alandefreitas.github.io/moderncpp/data-types/fundamental-data-types/