Hacker News new | ask | show | jobs
by larsu 5717 days ago
Bit Hack #6. Turn off the rightmost 1-bit.

Now it finally gets more interesting!!! Bit hacks #1 - #5 were kind of boring to be honest.

Does anybody know a practical use case for that? I have personally never encountered a situation were I needed to manipulate the right most 1-bit.

Otherwise it's a nice introduction to bit hacking.

4 comments

Let's say you use a bitmask for keeping track of free registers in a compiler. To "allocate" a register, you'll want to clear a bit, to indicate that the register is no longer free.

That's the context I learned this trick in. It's used in the Embarcadero (ex-Borland) compilers (Delphi, C++, etc.).

This is mainly useful for testing whenever given number is integral power of 2 (you gen zero in that case). Otherwise it might be useful for some special purpose counters/timers.
If you're handed a bit mask of events or flags then it can be used to iterate through the bits that are set, rather than all the bits.

    while flags!=0:
        right_most = flags & (-flags)
        process(right_most)
        flags &= ~right_most
Perhaps you are using a microcontroller with memory-mapped control registers?