Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 按位存取實作:把一個 byte 用出八倍價值

在某個創業專案中,為了節省網路頻寬,資料在網路上傳輸時必須做到緊湊存取。其實在國防、科研、航天、軍工等領域,類似需求也相當普遍。

所謂緊湊存取,就是不按「一個 byte 一個 byte」來存,而是按位(bit)來存。舉例來說,一個 byte 可以裝下 8 個 bool 資訊,等於把空間利用率拉高到八倍。廢話少說,直接看程式碼(提醒:以下演算法仍有優化空間)。

函式定義

// 從 buffer 讀一個位
void ReadOneBit(byte* pBuffer, int nStart, /* out */ int& nEnd, /* out */ byte& retByte);

// 從指定 buffer 讀任意長度的資料,支援任意型別
template<typename T>
void ReadDataFromBuffer(byte* pBuffer, int nStart, byte btLength,
                        /* out */ int& nEnd, /* out */ T& retData);

// 從指定 buffer 讀取一段字串
void ReadStringFromBuffer(byte* pBuffer, int nStart, int nCount,
                          /* out */ int& nEnd, /* out */ char* pRetData);

// 向 buffer 寫一個位
void WriteOneBit(byte* pBuffer, byte btData, int nStart, /* out */ int& nEnd);

// 向指定 buffer 寫入任意一段資料
template<typename T>
void WriteDataToBuffer(byte* pBuffer, T tData, int nStart, byte btLength,
                       /* out */ int& nEnd);

// 向指定 buffer 寫入一段字串
void WtriteStringToBuffer(byte* pBuffer, char* pchar, int nStart, int nCount,
                          /* out */ int& nEnd);

讀取:從單一位到任意型別

void ReadOneBit(byte* pBuffer, int nStart, /* out */ int& nEnd, /* out */ byte& retByte)
{
    byte btData = pBuffer[nStart / 8];   // 先取出所在的 byte
    btData = btData << nStart % 8;       // 把目標位移到最高位
    retByte = btData >> 7;               // 再右移 7 位取出
    nEnd = nStart + 1;
}

template<typename T>
void ReadDataFromBuffer(byte* pBuffer, int nStart, byte btLength,
                        /* out */ int& nEnd, /* out */ T& retData)
{
    retData = 0;
    if (btLength > sizeof(T) * 8) return;   // 長度別超出型別容量

    byte btData;
    T tData;
    while (btLength--){
        ReadOneBit(pBuffer, nStart, nStart, btData);
        tData = btData << btLength;
        retData |= tData;
    }
    nEnd = nStart;
}

void ReadStringFromBuffer(byte* pBuffer, int nStart, int nCount,
                          /* out */ int& nEnd, /* out */ char* pRetData)
{
    for (int nIndex = 0; nIndex < nCount; nIndex++){
        ReadDataFromBuffer(pBuffer, nStart, 8, nStart, pRetData[nIndex]);
    }
    nEnd = nStart;
}

寫入:位元運算的兩種面貌

void WriteOneBit(byte* pBuffer, byte btData, int nStart, /* out */ int& nEnd)
{
    int nSet = nStart / 8;
    byte c = pBuffer[nSet];
    switch (btData){
    case 1:
        c |= (1 << (7 - nStart % 8));            // 置 1
        break;
    case 0:
        c &= (~(1 << (7 - nStart % 8)));         // 清 0
        break;
    default:
        return;
    }
    pBuffer[nSet] = c;
    nEnd = nStart + 1;
}

寫入任意型別時,作者特別處理了位元序(endianness)的問題。大端模式下可以從低位元順序寫入;但在小端機上,記憶體中數值的 byte 排列是反過來的,因此必須先寫出不足一個 byte 的餘數部分(nRin),再由高位 byte 往低位 byte 反向寫出(nSet),順序顛倒才不會出錯:

template<typename T>
void WriteDataToBuffer(byte* pBuffer, T tData, int nStart, byte btLength,
                       /* out */ int& nEnd)
{
    // 小端機模式:寫 buffer 時不能順序寫位
    byte btDataLength = sizeof(T);
    if (btLength > sizeof(T) * 8) return;    // 校驗長度是否越界

    byte* ptData = (byte*)&tData;           // 將待寫資料轉為 byte*

    int nSet = btLength / 8;                 // 完整 byte 數
    int nRin = btLength % 8;                 // 餘數位元

    byte bitData, byteData;
    int nTempEnd;

    // 先寫 rin 部分
    byteData = ptData[nSet];
    while (nRin--){
        ReadOneBit(&byteData, 7 - nRin, nTempEnd, bitData);
        WriteOneBit(pBuffer, bitData, nStart, nStart);
    }

    // 再寫完整的 Set 部分,由高位 byte 遞減
    while (nSet){
        byteData = ptData[--nSet];
        int i = 0;
        while (i != 8){
            ReadOneBit(&byteData, i++, nTempEnd, bitData);
            WriteOneBit(pBuffer, bitData, nStart, nStart);
        }
    }
    nEnd = nStart;
}

void WtriteStringToBuffer(byte* pBuffer, char* pchar, int nStart, int nCount,
                          /* out */ int& nEnd)
{
    for (int nIndex = 0; nIndex < nCount; nIndex++){
        WriteDataToBuffer(pBuffer, pchar[nIndex], nStart, 8, nStart);
    }
    nEnd = nStart;
}

重點回顧

整套機制的默契是:所有函式都用「傳入起始位元位置、傳回結束位元位置」的方式串接,因此呼叫端只要把上一次的 nEnd 當成下一次的 nStart,就能在 buffer 中連續地塞入 bool、整數、浮點數與字串,而不必擔心跨 byte 邊界。

若真要優化,最有效的一步是放掉逐位元的 while 迴圈,改成一次處理一個 byte 的遮罩運算(mask + shift),並在編譯期用 if (btLength == 8) 之類的特化分支加速;另外把 nStart / 8 與 nStart % 8 合併成一次除法,也能少一點運算。

Copyright © Linux教程網 All Rights Reserved