位操作:位的结算范围 [英] bit manipulation: clearing range of bits

查看:95
本文介绍了位操作:位的结算范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用文本接受记者采访时preparing,破译编码访谈由盖尔·麦克道尔Laakman。在部分覆盖位操作,也有提供的两个函数,但我不明白它是如何工作的。

I'm preparing for an interview using the text, "Cracking the Coding Interview" by Gayle Laakman McDowell. On the section covering bit manipulation, there are two functions that are provided, but I don't quite understand how it works.

// To clear all bits from the most significant bit through i (inclusive), we do:
int clearMSBthroughI(int num, int i) {
    int mask = (1 << i) - 1;
    return num & mask;
}

// To clear all bits from i through 0 (inclusive), we do:
int clearBitsIthrough0(int num, int i) {
    int mask = ~(((1 << (i+1)) - 1);
    return num & mask;
}

在第一个功能,我明白了什么(1 LT;&LT; I)的确,当然,但是我不知道是怎么从这个减去1值影响位(即(1 LT;&LT; I) - 1))。

In the first function, I understand what (1 << i) does of course, but what I'm not sure of is how subtracting 1 from this value affects the bits (i.e., (1 << i) - 1)).

我基本上都用第二个功能同样的困惑。要什么效果,特别是对位,的确减去1从((1 <<;&LT;?(我+ 1))从我的理解,((1 <<;&LT;?(我+ 1))结果在一个上位,左移I + 1倍 - 这是什么用1减去这个做

I basically have the same confusion with the second function. To what effects, specifically on the bits, does subtracting 1 from ((1 << (i+1)) have? From my understanding, ((1 << (i+1)) results in a single "on" bit, shifted to the left i+1 times--what does subtracting this by 1 do?

谢谢,我希望这是明确的!请让我知道,如果有任何其他问题。

Thanks and I hope this was clear! Please let me know if there are any other questions.

对于那些谁一些机会,有我引用的文字,这是第91页的第5版。

For those who by some chance have the text I'm referencing, it's on page 91 in the 5th Edition.

推荐答案

让我们假设 I = 5

(1 LT;&LT; I)给你 0100000 1是摆在第6位的位置

(1 << i) give you 0100000 the 1 is placed in the 6th bit position

所以,现在如果我们。减去 1 从它,然后我们得到 0011111 ==>只有5第一位被设置为 1 和其他设置为 0 ,这就是我们如何让我们的面具

so now if we substract 1 from it, then we get 0011111 ==> only the 5 first bit are set to 1 and others are set to 0 and that's how we get our mask

结论:一个捐赠 I (1 LT;&LT; I)-1 会给你一个与面膜我设置为 1 第一位和其他设置为 0

Conclusion: for a giving i the (1 << i) -1 will give you a mask with the i first bits set to 1 and others set to 0

这篇关于位操作:位的结算范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆