Reputation: 3850
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.
Upvotes: 3
Views: 481
Reputation: 1412
It would work. I suppose it's a matter of taste whether your proposal or the code given is simpler. You will need 3 lines, this fuction has 2, and no branching, which could be seen as simpler. The code pictured may be faster, though it may be hard to come up with a program in which the difference is measurable.
Upvotes: 4