从寄存器中指定位置取指定位数值

///
//  GetBitSlice - Get a bit slice from a stream of bytes
//  Input:  pBuffer - buffer containing data stream
//          cbBuffer - size of buffer in bytes
//          dwBitOffset - bit offset from start of buffer
//          ucBitCount - number of bits (less than or equal to 32)
//  Output:
//
//  Return: returns a DWORD contain the bit slice shifted to fill the least significant bits
//  Notes:  will raise an SEH exception if integer overflow occurs
///

DWORD GetBitSlice(PUCHAR pBuffer, ULONG cbBuffer, DWORD dwBitOffset, UCHAR ucBitCount)
{
    UCHAR rgbShifted[4] = { 0 };
 DWORD dwUsedBytes; // How many bytes have valid data.
 DWORD dwLastByteIndex;
 DWORD dwRemainderShift;
 DWORD dwRet;

    if (ucBitCount > 32) {
        DEBUG_CHECK(FALSE, (TEXT("GetBitSlice: invalid number of bits /n")));
        return 0;
    }

    // Shift the pBuffer down by dwBitOffset bits.
    ShiftBytes(pBuffer, cbBuffer, dwBitOffset, rgbShifted);

    if (ucBitCount % 8 == 0) {
        // Return a byte multiple.
        dwUsedBytes = ucBitCount / 8;
    }
    else {
        // Clear the last used byte of upper bits.
        dwLastByteIndex = (ucBitCount - 1) / 8;
        dwRemainderShift = 8 - (ucBitCount % 8);
        rgbShifted[dwLastByteIndex] <<= dwRemainderShift;
        rgbShifted[dwLastByteIndex] >>= dwRemainderShift;
        dwUsedBytes = dwLastByteIndex + 1;
    }

    // Clear the unused bytes.
    if (dwUsedBytes != sizeof(rgbShifted)) {
        memset(rgbShifted + dwUsedBytes, 0, sizeof(rgbShifted) - dwUsedBytes);
    }

    memcpy(&dwRet, rgbShifted, sizeof(dwRet));

    return dwRet;
}

 

static
VOID ShiftBytes(PBYTE pbInput, ULONG cbInput, DWORD dwBitOffset, PBYTE pbOutput)
{
 DWORD dwRemainderShift;
    DWORD dwByteIndex;
 DWORD dwEndIndex;
 DWORD dwCurrOutputIndex = 0;
 
 dwByteIndex = dwBitOffset / 8;
    dwBitOffset %= 8;

    dwRemainderShift = 8 - dwBitOffset;

    // Only copy 4 bytes max.
    dwEndIndex = min(dwByteIndex + sizeof(DWORD), cbInput);
   
    while (dwByteIndex < dwEndIndex) {
        pbOutput[dwCurrOutputIndex] = pbInput[dwByteIndex] >> dwBitOffset;

        ++dwByteIndex;

        if (dwByteIndex != cbInput) {
            BYTE bTemp = pbInput[dwByteIndex];
            bTemp <<= dwRemainderShift;
            pbOutput[dwCurrOutputIndex] |= bTemp;
        }

        ++dwCurrOutputIndex;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值