dongshou7903 2016-01-07 01:56
浏览 131
已采纳

左移和右移按位运算符>>和<<的用法是什么

I understand the whole, it shifts the bits over

0000 0000 0000 0000 0000 0000 0000 0111 << 1
0000 0000 0000 0000 0000 0000 0000 1110

But why would you want to use these left and right shift operators instead of just typing out the number, where does using these operators actually have a benefit.

I see a lot of answers on Stackoverflow and what the operator accomplishes, but nobody ever says WHY they would use it over just typing out 12345 so like I said, why use them and what is their benefit over just typing the number out you're trying to get?

I came across this code while browsing a package on github:

// ClientVersion is the protocol version that Client implements.
const ClientVersion = 1<<16 | 3<<8 | 0

Which the number comes out to be: 66304

So if this is a constant why not just type const ClientVersion = 66304 why use the operators.

  • 写回答

2条回答 默认 最新

  • duanfaxin7014 2016-01-07 02:07
    关注

    If you assume a an integer, then a << x multiplies a by 2^x and a >> x divides b by 2^x, where you use an integer division.

    In the case that you described I see no real benefit of using 1<<16 | 3<<8 | 0 instead of 66304 (except of show-off that you can use bitwise operators, which in my stupid opinion is stupid).

    But there are ways where I think that they are justifiable (take a look at this question about iota constants).

    A couple of other examples (not only related to Go):

    • check if n-th bit is set x & (1<<n)
    • set the n-th bit x | (1<<n)
    • many other manipulations with n-th bit.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。