C language algorithms to convert the decimal numbers into binary numbers

Lead: In the C language is not the hexadecimal number of other tools or methods for the direct output of binary, octal output can be% o, can be output as hexadecimal% x, the output is a binary going our own solved. Here to tell you about how to program to convert decimal numbers to binary numbers.

 

First show you the source code:

#include <stdio.h>
void main()
{
    //进制转换函数的声明
    int transfer(int x);
    int x;
    printf("请输入一个十进制数:");
    scanf("%d",&x);
    printf("转换成二进制数是:%d\n",transfer(x));
}
int transfer(int x)
{
    int p=1,y=0,yushu;
    while(1)
    {
        yushu=x%2;
        x/=2;
        y+=yushu*p;
        p*=10;
        if(x<2)
        {
            y+=x*p;
            break;
        }
    }
    return y;
}

The algorithm embodied in the body of the function, uses an infinite loop while (1) when the result out of the loop. Variable yushu remainder is generated every time the inner loop, the variable x each cycle will be given a new value, the value of this new business is generated in each cycle. When commercially produced is less than 2 which produce the final result (binary number), and then out of the loop.

For example: If the function argument to 7, with an argument is divided by 27 to obtain the first cycle produces a remainder of 1, commercially produced by the first cycle is 3; cycle produces a quotient of 3 divided by 2 , and the remainder is generated in the second cycle is 1, the second cycle business generated one.

Y variable storage is a certain skill, because the remainder are each generated less than 2 and is the last bit binary numbers need to show up, so every time the remainder of the cycle should be reasonably produced for storage. The first remainder produced on the bit, the remainder produced in the second ten, the remainder of the third produced on one hundred ...... and so on until a cycle resulting quotient is less than 2 that business, and finally the highest level of less than 2 in. P is the variable effect of the control bits, the initial value of the variable y is set to 0, the initial value of the variable p is set to 1, the inner loop variable p each are 10 raised to a power, let each inner loop variable y plus yushu * p, so to achieve a bit of the remainder stored. Finally, the supplier by p is less than 2 added to the variable y to give the final binary number.

For example: Example 7 or in the independent variable, after the first cycle the value of y 1, y before the if statement. 11 is a second cycle, y is the value becomes 111, 111 is the if statement 7 binary number.

 

Note: The variable p is multiplied by itself should be placed after yushu * p variable y plus! The order can not be reversed!

Published 72 original articles · won praise 203 · views 90000 +

Guess you like

Origin blog.csdn.net/weixin_41676881/article/details/80745177