1. 程式人生 > 其它 >C++大小端轉換程式

C++大小端轉換程式

技術標籤:c++

C++大小端轉換的程式,用的模板,暫時不考慮有符號的,unsigned short,unsigned long, unsigned long long型別的資料都可以轉換。

//  整數大小端轉換 適用2 4 8個位元組數值
template <typename T>
static T transBytes(T arg)
{
    int len = sizeof (T);
    if (len <= 1)
        return arg;
    const T constNum = 0xFF;
    T targetNum, tempNum;
    T retNum = 0;
    for (int i = 0; i < len; ++i)
    {
        targetNum = constNum << (i * 8);
        tempNum = arg & targetNum;
        if (i < len / 2)  //  左移
            tempNum <<= (8*(len - 1 - 2*i));
        else  //  右移
            tempNum >>= (8*(1 + 2*i - len));
        retNum += tempNum;
    }
    return retNum;
}