Created
November 16, 2019 07:54
-
-
Save qrealka/3905ee2d69833e4a70a3bdee795ae30d to your computer and use it in GitHub Desktop.
struct binding for bitwise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdint> | |
#include <iostream> | |
#include <tuple> | |
#include <type_traits> | |
template <typename T> | |
using unsigned_of = std::conditional_t< | |
(sizeof(T) == 1), uint8_t, | |
std::conditional_t<(sizeof(T) == 2), uint16_t, | |
std::conditional_t<(sizeof(T) == 4), uint32_t, | |
std::conditional_t<(sizeof(T) == 8), | |
uint64_t, void>>>>; | |
template <typename Integer> | |
constexpr auto bytes_of(Integer i) { | |
unsigned_of<Integer> value = static_cast<unsigned_of<Integer>>(i); | |
if constexpr (sizeof(value) == 1U) { | |
return std::tuple<uint8_t>(value); | |
} else if constexpr (sizeof(value) == 2U) { | |
return std::tuple<uint8_t, uint8_t>(value >> 8U, value & 0x00FF); | |
} else if constexpr (sizeof(value) == 4U) { | |
return std::tuple<uint8_t, uint8_t, uint8_t, uint8_t>( | |
value >> 24U, (value >> 16U) & 0xFF, (value >> 8U) & 0xFF, | |
value & 0xFF); | |
} else if constexpr (sizeof(value) == 8U) { | |
return std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, | |
uint8_t, uint8_t>( | |
(value >> 56U) & 0xFF, (value >> 48U) & 0xFF, (value >> 40U) & 0xFF, | |
(value >> 32U) & 0xFF, (value >> 24U) & 0xFF, (value >> 16U) & 0xFF, | |
(value >> 8U) & 0xFF, value & 0xFF); | |
} | |
} | |
int main() { | |
auto [a, b, c, d] = bytes_of(0x04'03'02'01); | |
std::cout << std::hex << static_cast<int>(a) << ',' << static_cast<int>(b) | |
<< ',' << static_cast<int>(c) << ',' << static_cast<int>(d) << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment