n个左位C中的二进制位

问题描述 投票:0回答:1

获得函数getLeftBits(int n,int num),我需要从左返回num位,例如:

getLeftBits(7,31) --> 3  
getLeftBits(-1,2) --> 3

我每n个都轻松处理> 0:n >> (32 - num)但是当n <0有一些问题。

有什么建议吗?

c binary bit-manipulation
1个回答
0
投票

如果我很好理解,您想查看数字的二进制表示形式的最左边的n位。

大多数实现将使用算术右移而不是逻辑右移。您需要将数字强制转换为无符号整数,以防止此行为。

unsigned getLeftBits(int n, int num)
{
    return n >> (32 - num);
}

unsigned getLeftBits1(int n, int num)
{
    return (unsigned)n >> (32 - num);
}

getLeftBits:
        mov     ecx, 32
        mov     eax, edi
        sub     ecx, esi
        sar     eax, cl              <-------here
        ret
getLeftBits1:
        mov     ecx, 32
        mov     eax, edi
        sub     ecx, esi
        shr     eax, cl              <-------here            
        ret
© www.soinside.com 2019 - 2024. All rights reserved.