chr*_*irk 5 c++ performance templates bit-manipulation
template<int size>
inline void* byteswap(void* __x);
template<>
inline void* byteswap<2>(void* __x)
{
return (*(uint16*)__x >> 8) | (*(uint16*)__x << 8);
}
template<>
inline void* byteswap<4>(void* __x)
{
return (byteswap<4>(__x & 0xffff) << 16) | (bswap_16 (__x >> 16));
}
template<typename T>
inline T byteswap(T& swapIt)
{
return (T*)byteswap<sizeof(T)>(swapIt);
}
int main() {
uint32 i32 = 0x01020304;
uint16 i16 = 0x0102;
byteswap(i32);
byteswap(i16);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以上显然甚至无法编译。我很困惑,因为似乎我需要 void* 作为函数的参数,而当我需要调用 byteswap<2> 但有参考时,byteswap<4> 中的事情有点难看。
知道如何使这个看起来漂亮吗?它是否有可能实现(使用内联或其他技巧)使其性能与直接进行位操作一样?
这就是我编码的方式:
#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
}
Run Code Online (Sandbox Code Playgroud)
换句话说,我不会像您那样使用 size 作为模板参数。
编辑
抱歉,我的第一个代码是完全错误的 wrt/uint32 交换。