Practical applications of bit shifting

落花浮王杯 提交于 2019-11-30 15:54:44

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.

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

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!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!