I need help on Bit Twiddling

前端 未结 2 416
暗喜
暗喜 2021-01-25 19:17

I love to see people writing Bit Twiddling code but I just can\'t understand it at all. Gone through Hacker\'s Delight and http://graphics.stanford.edu/~seander/bithacks.html, b

相关标签:
2条回答
  • 2021-01-25 19:56

    What is the easiest way to calculate the output of bits for example 1 | 2 = 3.

    Write out the numbers as binary. This is how the numbers are really represented.

      00000001
    | 00000010
    = 00000011
    
    0 讨论(0)
  • 2021-01-25 20:08

    You're gonna have to study a little, but here's a little cheat sheet to know the number in binary form

    128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
    

    If you want 3, go from left to right, filling up in the spaces that contains the values you need to create the number 3

    128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
                                 X   X
    

    2 + 1 = 3 so you replace the ones marked with X with 1s and the rest with 0s

    00000011
    

    The same for the number 2:

    128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
                                 X
    

    And the binary result is.

    00000010
    

    For the number 47:

    128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
                X        X   X   X   X
    

    Binary result:

    00101111
    

    This is not a rule, or formula or anything. It's just something to help you convert numbers a little faster, and practice it in your head. You'll still need to study a lot if you want to play with bits :-)

    0 讨论(0)
提交回复
热议问题