title: Changing integer to binary string of digits
body: <p>I'm currently working on a simulation of the MIPS processor in C++ for a comp architecture class and having some problems converting from decimal numbers to binary (signed numbers both ways). Everything's working fine until the very last bit because my current algorithm falls into out of bounds areas for int on 1&lt;&lt;=31. Just need a nudge in the right direction to get it up and running. Thanks!</p>
  
  <pre><code>//Assume 32 bit decimal number
  string DecimalToBinaryString(int a)
  {
      string binary = "";
      int mask = 1;
      for(int i = 0; i &lt; 31; i++)
      {
          if((mask&amp;a) &gt;= 1)
              binary = "1"+binary;
          else
              binary = "0"+binary;
          mask&lt;&lt;=1;
      }
      cout&lt;&lt;binary&lt;&lt;endl;
      return binary;
  }
  </code></pre>
  
  <p>I'm also including my other algorithm for completeness. I apologize for the lack of comments, but it's fairly straight forward.</p>
  
  <pre><code>int BinaryStringToDecimal(string a)
  {
      int num = 0;
      bool neg = false;
      if(a.at(0) == '1')
      {
          neg = true;
          for(int x = a.length()-1; x &gt;= 0; x--)
          {
              if(a.at(x) == '1')
                  a.at(x) = '0';
              else a.at(x) = '1';
          }
          a.at(a.length()-1) += 1;
          for(int x = a.length()-1; x &gt;= 0; x--)
          {
              if(a.at(x) == '2')
              {
                  if(x-1 &gt;= 0)
                  {
                      if(a.at(x-1) == '1')
                          a.at(x-1) = '2';
                      if(a.at(x-1) == '0')
                          a.at(x-1) = '1';
                      a.at(x) = '0';
                  }
              }
              else if(a.at(x) == '3')
              {
                  if(x-1 &gt;= 0)
                      a.at(x-1) += '2';
                  a.at(x) = '1';
              }
          }
          if(a.at(0) == '2')
              a.at(0) = '0';
          else if(a.at(0) == '3')
              a.at(0) = '1';
      }
      for(int x = a.length()-1; x &gt;= 0; x--)
      {
          if(a.at(x) == '1')
              num += pow(2.0, a.length()-x-1);
      }
      if(neg)
          num = num*-1;   
      return num;
   }
  </code></pre>
  
  <p>Also if anyone knows any good ways to go about writing these more efficiently I'd love to hear it. I've only had the two introductory programming classes but have been playing with different techniques to see how well I like their style.</p>