dongmeba4877 2014-02-11 16:38
浏览 21
已采纳

移位:有人可以解释这段代码的作用吗?

So, I'm reading a book on Go (The Way to Go by Ivo Balbaert), and in it there is a code sample:

const hardEight = (1 << 100) >> 97

Since I don't have Go installed on this machine, I decided to translate it to PHP to see the results (via http://writecodeonline.com/php/ since I don't have PHP installed on this machine either):

echo (1 << 100) >> 97;

The result for the above is 8....huh? So I wrote decided ok, lets write a for-loop from 0 to 100 and see the results:

for($i = 0; $i <= 100; $i++){
    echo $i . ": ";
    echo ($i << 100) >> 97;
    echo "<br>";
}

However, the results are:

0: 0
1: 8
2: 16
3: 24
4: 32
5: 40
6: 48
7: 56
8: 64
9: 72
10: 80
11: 88
12: 96
13: 104
14: 112
15: 120
16: 128
17: 136
18: 144
19: 152
20: 160
21: 168
22: 176
23: 184
24: 192
25: 200
26: 208
27: 216
28: 224
29: 232
30: 240
31: 248
32: 256
33: 264
34: 272
35: 280
36: 288
37: 296
38: 304
39: 312
40: 320
41: 328
42: 336
43: 344
44: 352
45: 360
46: 368
47: 376
48: 384
49: 392
50: 400
51: 408
52: 416
53: 424
54: 432
55: 440
56: 448
57: 456
58: 464
59: 472
60: 480
61: 488
62: 496
63: 504
64: 512
65: 520
66: 528
67: 536
68: 544
69: 552
70: 560
71: 568
72: 576
73: 584
74: 592
75: 600
76: 608
77: 616
78: 624
79: 632
80: 640
81: 648
82: 656
83: 664
84: 672
85: 680
86: 688
87: 696
88: 704
89: 712
90: 720
91: 728
92: 736
93: 744
94: 752
95: 760
96: 768
97: 776
98: 784
99: 792
100: 800

Can someone explain to me what is going on with the snippet? I know its bitshifting, but I don't understand bitshifting well enough to discern what is going on there. Thank you :)

  • 写回答

1条回答 默认 最新

  • douhei8633 2014-02-11 16:59
    关注

    Using 1 as an example(you loop through 0-100 but its the same principal for all) Starting with what is inside the brackets:

    (1 << 100)
    

    will do a left shift on the number 1 by 100 places. this gives you 1 followed by 100 zeros. then, this really large number(known as a googol) gets shifted right by 97 which leaves you with:

    1000
    

    which is the binary representation of the decimal number 8. For the other numbers, they are converted to binary first(so 2 becomes 10, 3 becomes 11 etc..) and the calculation is applied.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图