字符到二进制(ASCII)的递归函数

时间:2014-10-01 20:31:49

标签: c function recursion binary ascii

我以2美元的价格在院子里买了一本编程书,因为我一直想学习如何编码,但没有学校的资金和资源。我已经完成了前几章,但我也有解决我正在处理的问题的方法。但是当章节摘要开始列出问题时,本章缺少一些页面。我想知道你们是否可以帮助我。

这是问题所在。注意:需要使用递归函数。

#include <stdio.h>
#include <stdlib.h>

void binaryPrinter(int value, int *numberOfOnes);
void print(char c);

//You do not need to modify any code in main
int main()
{
    char value;
    int result = 1;

    while(result != EOF)
    {
        result = scanf("%c",&value);

        if(result != EOF && value != '\n')
        {
            print(value);
        }
    }
}

//@hint: This is called from main, this function calls binaryPrinter
void print(char c)
{

}

//@hint: this function is only called from print
void binaryPrinter(int value, int *numberOfOnes)
{

}

1 个答案:

答案 0 :(得分:2)

void print(char c)
{
    int n = CHAR_BIT;
    binaryPrinter((unsigned char)c, &n);
    putchar('\n');
}

void binaryPrinter(int value, int *numberOfOnes)
{
    if((*numberOfOnes)--){
        binaryPrinter(value >> 1, numberOfOnes);
        printf("%d", value & 1);
    }
}