Bitwise hacks



  • I’ve taken it upon myself to explore the world of bit manipulation and bitwise operations. This is primarily in the C language but most of the techniques apply to any language that supports gate operations like AND (conjunction), OR (disjunction), NOT (negation), and etc… I’ll be posting my bitwise adventures in this thread for fun.

    Bitwise AND can be used to extract bits from a binary number like so:

    1111 1010
    &
    0000 1111
    ------------------
    0000 1010
    

    Here we cleared out the top nibble (4 bits) and retained the low nibble. This could also have been accomplished with an XOR like so:

    1111 1010
    ^
    1111 0000
    -----------------
    0000 1010
    

    Turns out, all of these bit-level operations or “hacks” can be accomplished multiple ways due to De Morgan’s laws.


Log in to reply