Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think it's unfortunate that the article does not provide real examples where these bit hacks are used. Why would I want to be able to unset the left-most 1 bit of a series of bits?


Thanks, that's a good question and comment. I'll try to write another part of the article with applications to these hacks! There are plenty in embedded engineering, kernel programming, cryptographic algorithms, space efficient data structures, fast image processing algorithms, and in plenty other computing areas.

To answer your question, why you'd want to set/unset the right-most 1-bit, suppose you have a space efficient 8 bit data structure that represents 8 devices. Each bit represents if a device is on and off. And you want to turn off the right-most device. Then you could use that hack. Or for example, you want to linearly turn on devices from 1st to 8th, then you can just turn on the rightmost bit eight times, and turn off in the same manner. Or you could have some crazy device that puts data at some memory location and waits you to clear the rightmost bit before it puts new data at that location. Or you have a number system coded in your byte in such a way that rightmost low order bit is always the sign (or some other craziness).


When, given a bit-vector representation of 8 devices, would I want to do something with the "right-most" of those devices?


for example, those 8 devices were 8 LEDs, some of them on, and you'd want to turn the rightmost led off. :)

edit: i'll look into more serious applications when i write that article on bit trick applications.


Ok, lights are a good example.


Two cases are when talking to devices which use bits in a register to control behavior, and when the size of your data structure must be as compact as possible: http://miller.cs.wm.edu/lxr3.linux/http/ident?v=2.6.11.12;i=...


He didn't even talk about how to do the left-most bit, which is too bad, because getting the left-most bit is more useful than getting the right-most bit.


Unfortunately it is not possible to do that efficiently with just a few bit operations because of the following theorem:

Theorem. A function mapping words to words can be implemented with word-parallel add, subtract, and, or, and not instructions if and only if each bit of the result depends only on bits at and to the right of each input operand.

The proof and comments are in the Hacker's Delight book!

That's why it's not in the article.


I didn't take the article to be "with just a few bit manipulations", but rather "how to start working with bits". But yeah that's a sensible reason not to attempt it.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: