endian: avoid directly byteswapping signed ints

This commit is contained in:
Danny Robson 2015-01-10 20:08:07 +11:00
parent b58fdaea9d
commit 2640811e03

View File

@ -88,17 +88,22 @@ struct from_endian {
static_assert (std::is_integral<T>::value || std::is_enum<T>::value, static_assert (std::is_integral<T>::value || std::is_enum<T>::value,
"endian conversion is only defined for integrals currently"); "endian conversion is only defined for integrals currently");
auto u = static_cast< union {
typename std::conditional< typename sized_type<T>::sint sint;
std::is_signed<T>::value, typename sized_type<T>::uint uint;
typename sized_type<T>::sint, };
typename sized_type<T>::uint
>::type
> (v);
return static_cast<T> ( if (std::is_signed<T>::value)
(src == endian::LITTLE) ? ltoh (u) : btoh (u) sint = v;
); else
uint = v;
uint = (src == endian::LITTLE) ? ltoh (uint) : btoh (uint);
if (std::is_signed<T>::value)
return T (sint);
else
return T (uint);
} }
endian src; endian src;