Practical applications of bit shifting

前端 未结 4 520
-上瘾入骨i
-上瘾入骨i 2021-01-03 05:33

I totally understand how to shift bits. I\'ve worked through numerous examples on paper and in code and don\'t need any help there.

I\'m trying to come up

相关标签:
4条回答
  • 2021-01-03 05:48
    1. Quick multiplication and division by a power of 2 - Especially important in embedded applications
    2. CRC computation - Handy for networks e.g. Ethernet
    3. Mathematical calculations that requires very large numbers

    Just a couple off the top of my head

    0 讨论(0)
  • 2021-01-03 05:49

    One common use is to use an int/long as a series of flag values, that can be checked, set, and cleared by bitwise operators.

    Not really widely used, but in (some) chess games the board and moves are represented with 64 bit integer values (called bitboards) so evaluating legal moves, making moves, etc. is done with bitwise operators. Lots of explanations of this on the net, but this one seems like a pretty good explanation: http://www.frayn.net/beowulf/theory.html#bitboards.

    And finally, you might find that you need to count the number of bits that are set in an int/long, in some technical interviews!

    0 讨论(0)
  • 2021-01-03 05:51

    The most common example of bitwise shift usage I know is for setting and clearing bits.

    uint8_t bla = INIT_VALUE;
    
    bla |= (1U << N);   // Set N-th bit
    bla &= ~(1U << N);  // Clear N-th bit
    
    0 讨论(0)
  • 2021-01-03 05:56

    I would not agree that the most important example is endianness but it is useful. Your examples are valid.

    Hash functions often use bitshifts as a way to get a chaotic behavior; not dissimilar to your cryptographic algorithms.

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