-5

I'm not sure, especially, what the last line does. I saw it in a Python book.

from random import randint
random_bits = 0 
for i in range(64): 
    if randint(0, 1): 
        random_bits |= 1 << i
Nicholas
  • 2,560
  • 2
  • 31
  • 58
  • 2
    Have you tried running it? Reading the documentation on what those functions and operators do? What precisely don't you understand? Just reading the names of the things involved should give you a reasonable idea of what's happening; it's generating 64 random bits. – jonrsharpe Jul 24 '16 at 09:56
  • 2
    I find it hard to imagine the book provided this code with no explanation, or statement of purpose, whatsoever. – Michael Foukarakis Jul 24 '16 at 09:58
  • http://stackoverflow.com/questions/14295469/what-does-mean-pipe-equal-operator – Łukasz Rogalski Jul 24 '16 at 10:07
  • http://stackoverflow.com/questions/6385792/what-does-a-bitwise-shift-left-or-right-do-and-what-is-it-used-for – Łukasz Rogalski Jul 24 '16 at 10:08

2 Answers2

2

You have here 2 special operators:

  1. x << y which shift the binary representation of x by y places
  2. x |= y which do binaric or between x and y and store the result in x

With this knowledge you can see that your code produce a random 64 bits number. On each iteration it turn on the i'th bit with probability of 50%.

Graham
  • 7,431
  • 18
  • 59
  • 84
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
1

From the docs :

x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y

I think the rest should be trivial from the naming of variables

Zein Makki
  • 29,485
  • 6
  • 52
  • 63