Presumably the C ++ 20 standard will incorporate in type_traits
functionality to differentiate the architectures.
In that case your C ++ code might look something like this:
#include <type_traits>
#include <cstdint>
uint16_t ConvertBytesToShort(uint8_t msb, uint8_t lsb)
{
if( std::endian::native == std::endian::big )
return (static_cast<uint16_t>(lsb) << 8) + msb;
else if( std::endian::native == std::endian::little )
return (static_cast<uint16_t>(msb) << 8) + lsb;
else
// te faltaria tratar este caso
}
While we wait for the 3 years that remain until this standard sees the light you can use a solution such that:
C ++ 17
#include <cstdint>
constexpr bool is_big_endian()
{
union
{
uint32_t intDummy;
unsigned char c[4];
} uTest = { 0x01020304 };
return uTest.c[0] == 1;
}
uint16_t ConvertBytesToShort(uint8_t msb, uint8_t lsb){
if( is_big_endian() )
return (static_cast<uint16_t>(lsb) << 8) + msb;
else
return (static_cast<uint16_t>(msb) << 8) + lsb;
}
C ++ 11 and earlier
#include <cstdint>
bool is_big_endian()
{
union
{
uint32_t intDummy;
unsigned char c[4];
} uTest = { 0x01020304 };
return uTest.c[0] == 1;
}
uint16_t ConvertBytesToShort(uint8_t msb, uint8_t lsb){
if( is_big_endian() )
return (static_cast<uint16_t>(lsb) << 8) + msb;
else
return (static_cast<uint16_t>(msb) << 8) + lsb;
}