趣味100道C语言编程题num eight

将任一整数转换成二进制数

#include 
#define MAX_SIZE 1024

char * int2bin(int num)
{ 
    int i;
    char bin[MAX_SIZE];   

    for(i = 31;i >= 0;i--)
    {
        bin[i] = (num >> 1) & 1;
        num = num >> 1;
    }
    return bin;
}

int main()
{
    int num;

    printf("Please input an integer:\n");
    scanf("%d",&num);

    char * res = int2bin(num);

    printf("The binary of the integer is:%s",bin);

    return 0;
}
调试结果为:

Please input an integer:
1234567890
0100 1001 1001 0110 0000 0010 1101 0010 
思考拓展:

将任一整数转换成四进制和八进制数

#include 
#define MAX_SIZE 1024

char * int2four(int num)
{
    int i;
    int step = -1;
    int temp = 1;
    static char four[MAX_SIZE];

    while(num >= temp)
    {
        temp = temp * 4;
        step++;
    }

    temp = temp / 4;

    for(i = 0;i <= step;i++)
    {
        four[i] = num / temp + '0';
        num = num - (num / temp) * temp;
        temp = temp / 4;
    }
    
    four[step + 1] = '\0';
    return four;
}

char * int2oct(int num)
{
    int i;
    int step = -1;
    int temp = 1;
    static char oct[MAX_SIZE];

    oct[0] = '0';

    while(num - temp >= 0)
    {
        step++;
        temp = temp * 8;
    }

    temp = temp / 8;

    for(i = 0;i <= step;i++)
    {
        oct[i + 1] = num / temp + '0';
        num = num - (num / temp) * temp;
        temp = temp / 8;
    }

    oct[step + 2] = '\0';

    return oct;
}

int main()
{
    int num;

    printf("Please input an integer:\n");
    scanf("%d",&num);

    char * res1 = int2four(num);
    printf("The four of the integer is:%s\n",res1);

    char * res2 = int2oct(num);
    printf("The oct of the integer is:%s\n",res2);

    return 0;
}

调试结果为:

Please input an integer:
123456789
The four of the integer is:13112330310111
The oct of the integer is:0726746425




你可能感兴趣的:(趣味100道C语言程序题)