故事有點長,它是整數尾數普遍實施,原來的代碼是一樣的:如何用C++ 11月14日,以簡化這個實現
#ifdef _BIG_ENDIAN_
#define ENDIANUSHORT(src) (unsigned short)src
#define ENDIANULONG(src) (unsigned long)src
#define ENDIANUINT64(src) (unsigned long long)src
#else
#define ENDIANUSHORT(src) ((unsigned short)((((src)>>8)&0xff) |\
(((src)<<8)&0xff00)))
#define ENDIANULONG(src) ((unsigned long)((((src)>>24)&0xFF) |\
(((src)>> 8)&0xFF00) |\
(((src)<< 8)&0xFF0000) |\
(((src)<<24)&0xFF000000)))
#define ENDIANUINT64(src) ((unsigned long long)((((src)>>56)&0xFF) |\
(((src)>>40)&0xFF00) |\
(((src)>>24)&0xFF0000) |\
(((src)>> 8)&0xFF000000) |\
(((src)<< 8)&0xFF00000000LL) |\
(((src)<<24)&0xFF0000000000LL) |\
(((src)<<40)&0xFF000000000000LL) |\
(((src)<<56)&0xFF00000000000000LL)))
#endif //_BIG_ENDIAN_
template<
typename T,
typename std::enable_if<std::numeric_limits<T>::is_integer>::type* = nullptr>
T _endian(T& t) {
if (sizeof(T) == 2)
return ENDIANUSHORT(t);
else if (sizeof(T) == 4)
return ENDIANULONG(t);
else if (sizeof(T) == 8)
return ENDIANUINT64(t);
return t;
}
template<typename T>
void endian(T& t) { t = _endian(t); }
int main()
{
long lv = 123;
endian(lv);
......
}
它運作良好,但有在MSVC警告等作爲:
warning C4293: '>>': shift count negative or too big, undefined behavior
然後精製它爲: t替換_endian(T & t)隨下面的代碼定義:
static int64_t _endian(int64_t t) {
return ENDIANUINT64(t);
}
static uint64_t _endian(uint64_t t) {
return ENDIANUINT64(t);
}
static int32_t _endian(int32_t t) {
return ENDIANULONG(t);
}
static uint32_t _endian(uint32_t t) {
return ENDIANULONG(t);
}
static int16_t _endian(int16_t t) {
return ENDIANUSHORT(t);
}
static uint16_t _endian(uint16_t t) {
return ENDIANUSHORT(t);
}
static int8_t _endian(int8_t t) {
return t;
}
static uint8_t _endian(uint8_t t) {
return t;
}
現在沒有報警,但我認爲有2個缺點:
- 功能的實現是枯燥的,冗餘和inconcise。
- 也許有些情況下,不包括
我認爲C++ 11月14日可以提供一個優雅和短期實施完成它,你有什麼想法?
感謝。
你可能想看看進入升壓字節序庫。 –
感謝您的信息。 boost是非常有名的,但從我的觀點來看,我不想引入額外龐大的代碼庫實現,所以我不是boost的粉絲。 –
我也不介紹很多不必要的代碼。只要看看他們做了什麼;-) –