Search code examples
cradix

method to convert a int into a binary format in C without itoa?


how can i convert a integer with radix 10 to a binary string with C without having the itoa function?


Solution

  • You can print a '0' if the number is even or '1' if it is even, then divide by 2 and recurse. Only the other way around ... or something like that.

    Example with 13

        13 is odd  so print 1 and divide by 2 giving 6
         6 is even so print 0 and divide by 2 giving 3
         3 is odd  so print 1 and divide by 2 giving 1
         1 is odd  so print 1 and divide by 2 giving 0
         0 reached so stop and read the printing backwards
                 from this ^^^ column
    

    13 is 1101 in binary