3 ms·
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 pra
by larsu 16y 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.
- dfox 16y agoThis 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.
- barrkel 16y agoLet'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.).
- sliverstorm 16y agoPerhaps you are using a microcontroller with memory-mapped control registers?
- RiderOfGiraffes 16y agoIf 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