Convert decimal to binary in C

2020-02-01 03:10发布

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 dectobin(int value, char* output)
{
    int i;
    output[5] = '\0';
    for (i = 4; i >= 0; --i, value >>= 1)
    {
        output[i] = (value & 1) + '0';
    }
}

Any help would be much appreciated!

标签: c binary decimal
16条回答
疯言疯语
2楼-- · 2020-02-01 03:58
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.

查看更多
老娘就宠你
3楼-- · 2020-02-01 04:00
//decimal to binary converter
long int dec2bin(unsigned int decimal_number){
  if (decimal_number == 0)
    return 0;
  else
    return ((decimal_number%2) + 10 * dec2bin(decimal_number/2));
}
查看更多
手持菜刀,她持情操
4楼-- · 2020-02-01 04:01

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 <stdio.h>  
#include <string.h>  

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;  
} 
查看更多
Luminary・发光体
5楼-- · 2020-02-01 04:03
int main() 
{ 
 int n, c, k;
 printf("Enter an integer in decimal number system: ");
 scanf("%d", &n);
 printf("%d in binary number system is: ", n);
 for (c = n; c > 0; c = c/2) 
  {
   k = c % 2;//To
   k = (k > 0) ? printf("1") : printf("0");
  }
 getch();
 return 0; 
}
查看更多
登录 后发表回答