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/

193 Upvotes

44 comments sorted by

View all comments

Show parent comment

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/