Convert binary format string to int, in C

前端 未结 7 603
刺人心
刺人心 2020-12-01 21:21

How do I convert a binary string like \"010011101\" to an int, and how do I convert an int, like 5, to a string \"101\" in C?

7条回答
  •  星月不相逢
    2020-12-01 22:09

    For the 2nd part of the question, i.e. "how do I convert an int, like 5, to a string "101" in C?", try something like:

    void
    ltostr( unsigned long x, char * s, size_t n )
    {
      assert( s );
      assert( n > 0 );
    
      memset( s, 0, n );
      int pos = n - 2;
    
      while( x && (pos >= 0) )
      {
        s[ pos-- ] = (x & 0x1) ? '1' : '0'; // Check LSb of x
        x >>= 1;
      }
    }
    

提交回复
热议问题