Hi i am writing a program to convert a user entered integer number into its binary representation, the aim is to repeatedly ask the user to enter a value then output the number in binary and when 9999 is entered end program, i've managed to make it work with positive integers so far only it displays them backwards. I've read i need to use a shift operator to move the mask across 1 bit each time for this calculation but i cant seem to get it to work, at the moment it doesnt seem to make a difference with or without it. Any ideas please?
Thanks

{
    int num, result, remainder;
    int i = 1, z = 0;
    int mask = 1000000;
    while (i = 1){
//Request user input
  printf("\nEnter integer value:");
  scanf("%d",&num);
//calculation
  if (num != 9999){
      result = num / 2;
      remainder = num % 2;
      //while (result != 0)
          while (z < 32)
      {
          if (num & mask !=0)
           printf("1");
          else
              printf("0");
            (mask >> 1);
            num = result;
            result = num / 2;
            remainder = num % 2;
            z++;
      }
          z=0;
     //printf("%d\n",mask);
     
  }
  else break;
 
    }

Recommended Answers

All 2 Replies

You're over-complicating this a bit. Have a look at the following snippet and see if you can follow what it does:

for (j = NUMBEROFBITS-1; j >= 0; --j) {
        if (i & (1 << j))
            putchar('1');
        else
            putchar('0');
    }

NUMBEROFBITS is defined as the number of bits in an int for your system - for example let's say it's 32. The variable i is your input value.

ah i get it now, thats really helped me cut my code down and clear up my problem, thanks!

commented: For courtesy and for taking the time to mark the thread as solved. +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.