Implementing decimal binary output __c language in C language

Source: Internet
Author: User
Tags decimal to binary numeric value

As we all know, C in eight, decimal and hexadecimal can be easily implemented through%d,%o and%x, but only does not provide a fast way of binary output. Bo Master sorted out two kinds of simple implementation methods for reference. Method One: itoa function

The Itoa function converts a numeric value to a string and implements it by a specified conversion. (or use C to bring the code block HH)

#include <stdio.h>
#include <stdlib.h>
//Note You must call the Stdlib.h function library
int main (void) {
    int a=1000;
    Char str[30];
    Itoa (a,str,2);//2 is the conversion to 2-in-system
    printf ("%s", str);

    return 0;
Method Two: Short division

Short division, converting decimal to binary written calculation process is accomplished by simple code. There's no shortcut.

#include <stdio.h>
int main (void) {
    int a,b,k,i;
    int remainder[30];
    A remainder array is defined to collect the remainder of the short division and the reverse output of the stack.
    a=1000;
    k=0;
    while (a!=0) {
        b=a/2;
        k++;
        remainder[k]=a-b*2;
        A=A/2;
    };
    for (i=k;i>=1;i--) {
        printf ("%d", Remainder[i]); 

    return 0;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.