Converting an integer to binary in C

后端 未结 12 1099
别跟我提以往
别跟我提以往 2021-02-02 04:30

I\'m trying to convert an integer 10 into the binary number 1010.

This code attempts it, but I get a segfault on the strcat():

int int_to_bin(int k)
{
          


        
12条回答
  •  滥情空心
    2021-02-02 04:52

    short a;
    short b;
    short c;
    short d;
    short e;
    short f;
    short g;
    short h;
    int i;
    char j[256];
    
    printf("BINARY CONVERTER\n\n\n");
    
    //uses 
    
    while(1)
    {
    
    a=0;
    b=0;
    c=0;
    d=0;
    e=0;
    f=0;
    g=0;
    h=0;
    i=0;
    
    
    gets(j);
    i=atoi(j);
    if(i>255){
    printf("int i must not pass the value 255.\n");
    i=0;
    }
    if(i>=128){
    a=1;
    i=i-128;}
    if(i>=64){
    b=1;
    i=i-64;}
    if(i>=32){
    c=1;
    i=i-32;}
    if(i>=16){
    d=1;
    i=i-16;}
    if(i>=8){
    e=1;
    i=i-8;}
    if(i>=4){
    f=1;
    i=i-4;}
    if(i>=2){
    g=1;
    i=i-2;}
    if(i>=1){
    h=1;
    i=i-1;}
    
    printf("\n%d%d%d%d%d%d%d%d\n\n",a,b,c,d,e,f,g,h);
    }
    

提交回复
热议问题