title: Generate all combinations for pair of bits set to 1?
body: <p>I'm trying to generate all possible combinations for pair of 1's within given bit width.</p>
  
  <p>Let's say the bit width is 6, i.e. number 32. This is what I would like to generate:</p>
  
  <pre><code>000000
  000011
  000110
  001100
  001111
  011000
  011011
  011110
  110000
  110011
  110110
  111100
  111111
  </code></pre>
  
  <p>If I have variables:</p>
  
  <pre><code>var a = 1,
      b = 2;
      num = a | b;
  </code></pre>
  
  <p>and create a loop that I'll loop over <code>width - 1</code> times, and where I shift both <code>a &lt;&lt; 1</code> and <code>b &lt;&lt; 1</code>, I'll get all combinations for one pair. After that, I'm pretty much stuck.</p>
  
  <p>Could someone , please, provide some help.</p>
  
  <p><strong>Update: working example</strong><br>
  Based on Barmar's mathematical approach, this is what I managed to implement</p>
  
  <pre><code>var arr = [],
      arrBits = [];
  
  function getCombs(pairs, startIdx) {
      var i, j, val = 0, tmpVal, idx;
  
      if (startIdx + 2 &lt; pairs) {
          startIdx = arr.length - 1;
          pairs -= 1;
      }
  
      if (pairs &lt; 2) {
          return;
      }
  
      for (i = 0; i &lt; pairs-1; i++) {
          idx = startIdx - (i * 2);
          val += arr[idx];
  
      }
  
      for (j = 0; j &lt; idx - 1; j++) {
          arrBits.push((val + arr[j]).toString(2));
      }
  
      getCombs(pairs, startIdx-1);
  }
  
  (function initArr(bits) {
      var i, val, pairs, startIdx;
  
      for (i = 1; i &lt; bits; i++) {
          val = i == 1 ? 3 : val * 2;
          arr.push(val);
          arrBits.push(val.toString(2));
      }
  
      pairs = Math.floor(bits / 2);
      startIdx = arr.length - 1;
  
      getCombs(pairs, startIdx);
      console.log(arrBits);
  
  }(9));
  </code></pre>
  
  <p><strong>Working example on JSFiddle</strong><br>
  <a href="http://jsfiddle.net/zywc5/" rel="nofollow">http://jsfiddle.net/zywc5/</a></p>