Why Updating bit needs to clear the bit before setting it?

时间:2015-05-28 03:17:43

标签: bit-manipulation

While reading one coding book ("Cracking The Coding interview"), I came across one description about bit manipulation: update bit. It tells me to first clear the bit before setting it. Please see the attached picture for relevant book section. I am a bit confused about the purpose of this manipulation:
v seems to be the value for only 1 bit. If so, isn't it simpler to use a if else condition to decide whether to set the bit, rather than first clear the bit and then setting it?

Just want to make sure there is no logical flaw if to use if-else method mentioned above, compared to the book method of using two masks.

enter image description here

1 个答案:

答案 0 :(得分:4)

会起作用。我认为您的建议或给出的代码是否更简单是一个品味问题。你需要3行,这个功能有2行,没有分支,可以看作更简单。所示的代码可能更快,但可能很难想出一个可以测量差异的程序。