在 C 中获取二进制的 n 个 leftBits

get n leftBits of binary in C

得到函数 getLeftBits(int n,int num) 并且我需要 return num bits from left 例如:

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

我对每个 n>0 处理起来都很容易:n >> (32 - num)
但是当 n<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

https://godbolt.org/z/JuY_z4