C++ - Decimal to binary converting

后端 未结 29 3649
一向
一向 2020-11-28 18:53

I wrote a \'simple\' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there\'s a lot simpler way so can you show me? Here\'s the code:<

29条回答
  •  猫巷女王i
    2020-11-28 19:46

    The following is a recursive function which takes a positive integer and prints its binary digits to the console.

    Alex suggested, for efficiency, you may want to remove printf() and store the result in memory... depending on storage method result may be reversed.

    /**
     * Takes a unsigned integer, converts it into binary and prints it to the console.
     * @param n the number to convert and print
     */
    void convertToBinary(unsigned int n)
    {
        if (n / 2 != 0) {
            convertToBinary(n / 2);
        }
        printf("%d", n % 2);
    }
    

    Credits to UoA ENGGEN 131

    *Note: The benefit of using an unsigned int is that it can't be negative.

提交回复
热议问题