

Low Level Bit Hacks You Absolutely Must Know - pkrumins
http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know/

======
old-gregg
For those who enjoy these kind of problems I highly recommend "Hacker's
delight".

[http://www.amazon.com/Hackers-Delight-Henry-S-
Warren/dp/0201...](http://www.amazon.com/Hackers-Delight-Henry-S-
Warren/dp/0201914654)

~~~
pkrumins
Seconded. That is an amazing book.

I also recommend this much more complete article on bit hacks:

<http://graphics.stanford.edu/~seander/bithacks.html>

------
moe
How could they miss the classic. Swap two integers without a temporay var:

    
    
        a ^= b
        b ^= a
        a ^= b

~~~
pkrumins
oh no! totally forgot about this classic. :)

~~~
malloc
it doesn't deserve the time...

first only works if a is a different var than b

second it can be much slower than typical swap...

and finaly, it isn't clear what it does if your code is for others to read

~~~
patcdr
It still works fine if a and b are the same value.

Here's the general proof:

a ^= b (a = a ^ b, b = b)

b ^= a (a = a ^ b, b = b ^ (a ^ b) = a)

a ^= b (a = b ^ (a ^ b) = b ,b = a)

Now, let's replace all references initial values with constant c:

a ^= b (a = c ^ c = 0, b = c)

b ^= a (a = 0, b = c ^ 0 = c)

a ^= b (a = c ^ 0 = c, b = c)

Notice that at the end, you still end up with a = b = c. There are plenty of
reasons not to use this approach, but that ain't one of them.

~~~
jibiki
He meant if they are the same variable, not the same value. (E.g., you pass
pointers to your function.)

    
    
      int swap(int * a, int * b)
        {
        (*a)^=(*b);
        (*b)^=(*a);
        (*a)^=(*b);
        }
      int x = 15;
      int *y = &x;
      int *z = &x;
    
      swap(y,z);  //Now *y == 0

------
gamache
Also see the more advanced Bit Twiddling Hacks page:
<http://graphics.stanford.edu/~seander/bithacks.html>

------
pmorici
This article is kind of lame. 1 - 6 should be basic skills from undergrad CS
courses. Also the intro paragraph is a bait and switch,

"Instead of performing some operation (such as counting the 1 bits in an
integer) by looping over individual bits, these programming nuggets do the
same with one or two carefully chosen bitwise operations."

We never actually learn how to count set bits in an integer. (My initial
thought was look-up table but is there a better way?)

~~~
sgk284
The best solution I know of is:

    
    
      a, i = 11, 0
      while a > 0:
        a, i = a & a-1, i + 1
    

If there are k bits set out of n bits, it only does k iterations.

~~~
ralph
That's
[http://graphics.stanford.edu/~seander/bithacks.html#CountBit...](http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan)

------
Confusion
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?

~~~
pkrumins
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).

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

~~~
pkrumins
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.

~~~
tptacek
Ok, lights are a good example.

------
antipax
I guess I should be the one to provide the usual warning that C and C++ make
no guarantees about the in-memory representation of the built-in types, and
that this type of code can be very dangerous.

It is, however, very cool when it works.

~~~
Locke1689
Look up C99 and stdint.h. You will be pleasantly surprised.

~~~
antipax
Consider me educated.

------
spaghetti
my favorite is determine if an int is a power of 2: if(!(a & (a-1))){ // a is
a power of 2 }

~~~
swolchok
or a is negative.

------
aswanson
Is that a MOS 6502 in the image of the article? I want that chip.

------
Keyframe
you can also print binary in python like so:

    
    
      >>>print bin(12)
      0b1100
      >>>

~~~
pkrumins
Only Python 2.6 I think, and it does not print negatives very nicely (it
prints bin(-x) = -bin(x), instead of some number representation).

~~~
Keyframe
yes, you are right python >2.6 only

------
bkudria
AKA "how to write line noise".

~~~
pkrumins
Not quite!

These are embedded programmer tools of trade. For example, you don't want to
loop over bits to count number of bits in it (not covered in this article, but
will be in the next part of the article). It can be done with several shifts
and ANDs! Huge speedups!

Another example, finding the lowest order 1-bit in a 64bit integer - it can
take up to 64 iterations to find it with a loop. Instead it takes one AND and
one but inversion operation (= 2 ops total)! 32x speedup!

~~~
bcl
Absolutely! Some of the examples, depending on the core architecture, could
benefit from a table lookup, but all are good tools to have in the box.

~~~
pkrumins
Exactly! And you can get these questions even in job interviews. If you want
to score the intervieews, then you better know the quick ways!

~~~
ramchip
I like bit twiddling, but I'm not sure I'd take the job if a primary concern
of the interviewer is whether I know the quick way to find the lowest-order
bit in a 64-bit int...

------
notaddicted
I was expecting to see "None of them" as kind of a joke.

For a web app developer are these useful? For fun? yes. For profit? no. Title
should be Low Level Bit Hacks You May Find Interesting.

~~~
CodeMage
Maybe I'm missing something... Why the assumption that all (or even the
majority of) HN readers are interested only in developing web apps?

~~~
kscaldef
It suffices that just one such individual exists to invalidate the claim of
the title.

