Useful code snippet : GetBit & SetBit functions


If you want to manipulate the bit in BYTE array, following functions are useful to you.

BYTE GetBit(BYTE* pBuffer, int nBit)
{
    int bitOffset = nBit & 7;
    BYTE ret = pBuffer[nBit >> 3] >> bitOffset;
    ret &= 1;
    return ret;
}

void SetBit(BYTE* pBuffer, int nBit)   
{
    BYTE val = 1 << (nBit & 7);
    pBuffer[nBit >> 3] |= val;
}

For the GetBit, nBit is the bit offset you want to test.

nBit & 7 is equal to nBit % 8, it will get bit offset for input parameter nBit.

nBit >> 3 is equal to nBit / 8, it will get the byte offset in Byte array.

Why we use bit operations instead of mod and div operation? The reason is simple, for the bit operation, it will generate more fast and simple assembly code. You could see my build result like:

; 160  :     unsigned int modVal = i % 8;

    mov    eax, DWORD PTR _i$[ebp]
    xor    edx, edx
    mov    ecx, 8
    div    ecx
    mov    DWORD PTR _modVal$[ebp], edx

; 161  :
; 162  :     unsigned int andVal = i & 7;

    mov    eax, DWORD PTR _i$[ebp]
    and    eax, 7
    mov    DWORD PTR _andVal$[ebp], eax

The code is generated by VC2008 and disabled optimization. For mod operation "i % 8", it has "div" and will be slow then "i & 7".


发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注