title: Generate random number in given range from random bytes
body: <p>There are similar questions, but most of them too language specific. I'm looking for a general solution. Given some way to produce <em>k</em> random bytes and a number <em>n</em>, I need to produce a random number in range <em>1...n</em> (inclusive).</p>
  
  <p>What I've come up with so far:</p>
  
  <ol>
  <li>To determine the number of bytes needed to represent <em>n</em>, calculate </li>
  </ol>
  
  <p><code>f(n):=ceiling(ln(n)/8ln(2))=ceiling(0.180337*ln(n))</code></p>
  
  <ol start="2">
  <li>Get a random number in range in range <em>1...2^8f(n)</em> for 0-indexed bytes b[i]:</li>
  </ol>
  
  <p><code>r:=0
   for i=0 to k-1:
     r = r + b[i] * 2^(8*i)
   end for</code></p>
  
  <ol start="3">
  <li><p>To scale to <em>1...n</em> without bias:</p>
  
  <p><code>R(n,r) := ceiling(n * (r / 256^f(n)))</code></p></li>
  </ol>
  
  <p>But I'm not sure this does not create a bias or some subtle one-off error. Could you check whether this sound and/or make suggestions for improvements? Is this the right way to do this?</p>
  
  <p>In answers, please assume that there are no modular bit-twiddling operations available, but you can assume arbitrary precision arithmetics. (I'm programming in Scheme.)</p>
  
  <p><em>Edit: There is definitely something wrong with my approach, because in my tests rolling a dice yielded a few cases of 0! But where is the error?</em></p>