Here is how I code it:
#include <iostream> typedef unsigned short uint16; typedef unsigned int uint32; template<typename T> T byteswap(T value); template<> uint16 byteswap<uint16>(uint16 value) { return (value >> 8)|(value << 8); } template<> uint32 byteswap<uint32>(uint32 value) { return uint32(byteswap<uint16>(value) << 16) | byteswap<uint16>(value >> 16); } int main() { uint32 i32 = 0x11223344; uint16 i16 = 0x2142; std::cout << std::hex << byteswap(i32) << std::endl; // prints 44332211 std::cout << std::hex << byteswap(i16) << std::endl; // prints 4221 }
In other words, I would not use size as a template parameter, as you did.
EDIT
sorry my first code was just wrong wrt / uint32 swapping.
source share