Abdalrhman Loulou
Abdalrhman Loulou

Reputation: 13

Turning an integer to its binary representation using C?

I'm still a beginner in coding so I had this problem I'm trying to convert an integer into its binary representation

 #include <stdio.h>
 int main () {
   int x;
   printf("input the number\n");
   scanf("%d",&x);

   while(x!=0) {
     if (x%2)
       printf("1");
     else
       printf("0");
   }
   return 0;
 }

So it outputs like this 12=0011 but 12=1100 What is the problem and how do I solve it?

Upvotes: 0

Views: 12005

Answers (3)

Barath Ravikumar
Barath Ravikumar

Reputation: 5836

The Program Logic for the operation is wrong , try this

#include <stdio.h>
int main()
{
    int n, c, k;

    printf("Enter an integer in decimal number system\n");
    scanf("%d", &n);
    printf("%d in binary number system is:\n", n);

    for (c = 31; c >= 0; c--)
    {
        k = n >> c;

        if (k & 1)
            printf("1");
        else
            printf("0");
        }

        printf("\n");
    } 
    return 0;
}

Upvotes: 6

md5
md5

Reputation: 23699

A solution is to use recursion.

void put_binary (unsigned int x)
{
    if (x <= 1) 
    {
        putchar('0' + x);
    }
    else
    {
        put_binary (x / 2u);
        putchar ('0' + x % 2u);
    }
}

A more efficient way use bitwise operators (it prints every digits).

#define GET_BIT(x, i) (((x) >> (i)) & 1)

void put_binary (unsigned int x)
{
    unsigned int max = sizeof x * CHAR_BIT;
    unsigned int i;

    for (i = 0u; i < max; i++)  
    {
        putchar ('0' + GET_BIT (x, max - i - 1u));
    }
}

Upvotes: 3

cedrou
cedrou

Reputation: 2790

bool seeOne = false;
for (int i = 0; i < sizeof(int); i++)
{
  int bit = (x >> sizeof(int) - 1 - i) & 1;
  if (bit)
  { 
    print("1");
    seeOne = true;
  }
  else
  {
    if (seeOne)
      print("0");
  }
}

Upvotes: 1

Related Questions