Binary to decimal in c

后端 未结 5 608
Happy的楠姐
Happy的楠姐 2020-12-19 20:51

I have a simple code to convert binary to decimal numbers. In my compiler, the decomposition works just fine for number less than 1000, beyond the output is always the same

5条回答
  •  天涯浪人
    2020-12-19 21:43

    Shift left is the same than multiply by 2 and is more efficient, so I think it is a more c-like answer:

    #include 
    #include 
    
    int bin2int(const char *bin) 
    {
        int i, j;
        j = sizeof(int)*8;
        while ( (j--) && ((*bin=='0') || (*bin=='1')) ) {
            i <<= 1;
            if ( *bin=='1' ) i++;
            bin++;
        }
        return i;
    }
    
    int main(void) 
    { 
        char* input = NULL;
        size_t size = 0;
    
        while ( getline(&input, &size, stdin) > 0 ) {
            printf("%i\n", bin2int(input)); 
        }
        free(input);
    }
    

提交回复
热议问题