0
目前我有這個功能來交換數據的字節,以改變字節順序。儘可能有效地交換字節?
template<typename Type, unsigned int Half = sizeof(Type)/2, unsigned int End = sizeof(Type)-1>
inline void swapBytes(Type& x)
{
char* c = reinterpret_cast<char*>(&x);
char tmp;
for (unsigned int i = 0; i < Half; ++i) {
tmp = c[i];
c[i] = c[End-i];
c[End-i] = tmp;
}
}
這個函數會被幾百萬次的某些算法調用。因此,每一條可以避免的指令都是一件好事。
我的問題是:如何優化此功能?
posix版本有什麼問題? htons,ntohs,htonl,ntohl? –
他們不在標準的C++庫... – Vincent
我沒有說他們是 - 是你需要滿足的一個要求嗎?如果是這樣的話,請檢查這些的開源版本。 –