Convert decimal to binary in C

后端 未结 16 775
攒了一身酷
攒了一身酷 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:13

    First of all 192cannot be represented in 4 bits

    192 = 1100 0000 which required minimum 8 bits.

    Here is a simple C program to convert Decimal number system to Binary number system

    #include   
    #include   
    
    int main()  
    {  
        long decimal, tempDecimal;  
        char binary[65];  
        int index = 0;  
    
        /* 
         * Reads decimal number from user 
         */  
        printf("Enter any decimal value : ");  
        scanf("%ld", &decimal);  
    
        /* Copies decimal value to temp variable */  
        tempDecimal = decimal;  
    
        while(tempDecimal!=0)  
        {  
            /* Finds decimal%2 and adds to the binary value */  
            binary[index] = (tempDecimal % 2) + '0';  
    
            tempDecimal /= 2;  
            index++;  
        }  
        binary[index] = '\0';  
    
        /* Reverse the binary value found */  
        strrev(binary);  
    
        printf("\nDecimal value = %ld\n", decimal);  
        printf("Binary value of decimal = %s", binary);  
    
        return 0;  
    } 
    

提交回复
热议问题