The title may seem odd, but I'm not sure what else to call it. If you have suggestions please let me know and I'll edit.
Consider this
uint8_t lo = 0x11; // given
uint8_t hi = 0x22; // given
uint16_t word = (hi << 8) | lo; // constructed
But there's lots of given values, and they are either uint8_t
OR uint16_t
. That means the result (word
) should be uint16_t
OR uint32_t
, depending on the makeup of the vars I give it.
Is there anything like this? (bad syntax I know)
TYPE lo = 0x11;
TYPE hi = 0X22;
decl_int_type(sizeof(lo) + sizeof(hi)) word = (hi << sizeof(hi)) | lo;
Edit: I am not trying to solve a problem, or putting this in production. This came up as a discussion with a coworker and I was just asking for educational purposes.
Depending on what you want to do with the result, std::bitset
might help you accomplish what you need:
#include <bitset>
#include <iostream>
#include <iomanip>
#include <climits>
int main() {
char lo = 0x11;
unsigned short hi = 0X33;
using uint64_t = unsigned long long;
constexpr auto bits = (sizeof(lo) + sizeof(hi)) * CHAR_BIT;
std::bitset<bits> b = (uint64_t(hi) << sizeof(lo)*CHAR_BIT) | lo;
std::cout << b << "\n";
}
But whether this is useful depends heavily (completely, really) on why you want to do this, and what you want to do with the result.