title: Converting Integers to Binary in Ruby
body: <p>I'm working on a codewars kata and stuck with 2 test cases that are failing. </p>
  
  <p>The kata description is:
  Convert integers to binary as simple as that. You would be given an integer as a argument and you have to return its binary form. To get an idea about how to convert a decimal number into a binary number, visit here.</p>
  
  <p>Notes: negative numbers should be handled as two's complement; assume all numbers are integers stored using 4 bytes (or 32 bits) in any language.</p>
  
  <p>My code:</p>
  
  <pre><code>def to_binary(n)
    temp_array = []
    if n == 0
      temp_array &lt;&lt; 0
    elsif n &lt; 0
      n = n % 256
      while n &gt; 0 do
        temp_array &lt;&lt; (n % 2)
        n = (n / 2)
      end
      while temp_array.length &lt; 32 do
        temp_array &lt;&lt; 1
      end
    else
      while n &gt; 0 do
        temp_array &lt;&lt; (n % 2)
        n = (n / 2)
      end
    end
    binary = temp_array.reverse.join
  end
  </code></pre>
  
  <p>The test cases are:</p>
  
  <pre><code>Test Passed: Value == "10"
  Test Passed: Value == "11"
  Test Passed: Value == "100"
  Test Passed: Value == "101"
  Test Passed: Value == "111"
  Test Passed: Value == "1010"
  Test Passed: Value == "11111111111111111111111111111101"
  Test Passed: Value == "0"
  Test Passed: Value == "1111101000"
  Test Passed: Value == "11111111111111111111111111110001"
  Expected: "11111111111111111111110000011000", instead got: "11111111111111111111111111111000"
  Expected: "11111111111100001011110111000001", instead got: "11111111111111111111111111000001"
  Test Passed: Value == "11110100001000111111"
  </code></pre>
  
  <p>I suspect the tests that are failing are with negative integers because the first failing test's expected output is <code>11111111111111111111110000011000</code> which means that either the positive argument value was <code>4294966296</code> or it was negative.  If I run <code>to_binary(4294966296)</code> I get the expected output.</p>