Convert decimal to binary in C

后端 未结 16 692
攒了一身酷
攒了一身酷 2020-12-10 09:38

I am trying to convert a decimal to binary such as 192 to 11000000. I just need some simple code to do this but the code I have so far doesn\'t work:

void de         


        
相关标签:
16条回答
  • 2020-12-10 10:19

    The value is not decimal. All values in computer's memory are binary.

    What you are trying to do is to convert int to a string using specific base. There's a function for that, it's called itoa. http://www.cplusplus.com/reference/cstdlib/itoa/

    0 讨论(0)
  • 2020-12-10 10:19

    It looks like this, but be careful, you have to reverse the resulting string :-)

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    char output[256]="";
    
    int main()
    {
    int x= 192;
    int n;
    n = x;
    int r;
    do {
    r = n % 2;
    if (r == 1)
       strcat(output,"1");
    else strcat(output,"0");
    n = n / 2;
    }
    while (n > 0);
    
    printf("%s\n",output);
    }
    
    0 讨论(0)
  • 2020-12-10 10:20
    number=215
    a=str(int(number//128>=1))+str(int(number%128>=64))+
    str(int(((number%128)%64)>=32))+str(int((((number%12
    8)%64)%32)>=16))+str(int(((((number%128)%64)%32)%16)>=8))
    +str(int(((((((number%128)%64)%32)%16)%8)>=4)))
    +str(int(((((((((number%128)%64)%32)%16)%8)%4)>=2))))
    +str(int(((((((((((number%128)%64)%32)%16)%8)%4)%2)>=1)))))
    print(a)
    

    You can also use the 'if', 'else', statements to write this code.

    0 讨论(0)
  • #include <stdio.h>
    #include <stdlib.h>
    void bin(int num) {
        int n = num;
        char *s = malloc(sizeof(int) * 8);
        int i, c = 0;
        printf("%d\n", num);
    
        for (i = sizeof(int) * 8 - 1; i >= 0; i--) {
            n = num >> i;
            *(s + c) = (n & 1) ? '1' : '0';
            c++;
        }
        *(s + c) = NULL;
        printf("%s", s); // or you can also return the string s and then free it whenever needed
    }
    
    int main(int argc, char *argv[]) {
        bin(atoi(argv[1]));
        return EXIT_SUCCESS;
    }
    
    0 讨论(0)
提交回复
热议问题