-3

Hello people, Again, trying to create a program in C to help figuring what the equivalent binary-number to a given number is. I had no idea what to do first, I developed a little simple code for it. But the problem is that I had to put some improvisations into it AS code is (READ BACKWARDS). So regarding this, the code isn't really complete. Here's the code I came up with ..

#include <stdio.h>
void main()
{
int x,n;
printf("This program will help you find the equivalent binary-number to a given number \n");
printf("Enter number :");
scanf("%d",&n);
printf("The binary number to this number is(Read backwards) :");
for (;;n/=2)
    {
        x=n/2;
        if (x!=0) printf("%d",n%2);
        else {printf("%d\n",n%2); break;}
    }
}

Now the equivalent binary-number to 8 is 1000 and the program shows it backwards like 0001 and I have absolutely no idea how to to make it right. Any thoughts?

OsomePersan
  • 21
  • 1
  • 1
  • 4

3 Answers3

0

Use the shift right >> operator to read the number bit by bit. Then n & 1 tests if the bit is set or not.

  for (;n; n>>=1)
  {
    if (n & 1)
       printf("1");
    else
       printf("0");
  }
  puts("");
suspectus
  • 16,548
  • 8
  • 49
  • 57
  • Would shifting the bitmask instead be different in terms of speed? Apart from the value of `n` not being lost of course. – A Person Jan 13 '14 at 14:48
  • Don't know if there would be a performance benefit. If there is, it would be marginal. Also the code would then need to compute the integer type's bit length (for portability). – suspectus Jan 13 '14 at 15:11
  • Using `sizeof(n)<<3` to get the no. of bits would serve as the test in the for loop. A simple ternary operator would suffice for printing 1 or 0 instead of the if-else, and `n` wouldn't need to be modified. – A Person Jan 13 '14 at 16:04
  • The byte bitlength is platform dependant, it may not be eight bits. Any performance benefit being discussed here is minimal. Unless the loop is repeated a huge number of times, there is no discernable benefit. Your proposed solution is just as valid. – suspectus Jan 13 '14 at 16:30
  • As a tidbit, `((unsigned char)(~0)==0xff)` can be used to check if the size of 1 byte is 8 bits, as unsigned char is defined by the C standard to be one byte – A Person Jan 13 '14 at 16:50
0

An easy to understand solution would look like this:

/* compile with gcc -Wall -Werror -o bprint bprint.c */

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

void
bprint (int64_t n)
{
  int bit;

  /* Handle negative numbers as positive ones, printing a - sign */
  if (n < 0)
    {
      n = -n;
      printf ("-");
    }

  /* Skip leading zeros. Comment this bit out if you want */
  for (bit = 63; (n <= ((1LL << bit) - 1)) && (bit > 0); bit--);

  for (; bit >= 0; bit--)
    printf ("%c", (n & (1LL << bit)) ? '1' : '0');

  printf ("\n");
}

int
main (char **argv, int argc)
{
  int j;
  for (j = 0; j < 100; j++)
    bprint (j);
  exit (0);
}

The first for loop within the bprint function skips leading zero bits which are unneeded. The second for loop does the printing.

Note that this is far from the most efficient way to do it. A better way would be to note that an int64_t normally takes a string of at most 66 octets (leading minus, 64 bits, terminating zero). One could thus write the bits one by one into a fixed length array of characters, then write the terminating zero, and use printf with %s to print the result. And a practical function would either take a file handle, a FILE pointer, or return a string. Both of these are left as exercises for the reader; the purpose of the above is to show how the bit manipulation works. You could also use fewer brackets once you are confident with operator precedence.

abligh
  • 24,573
  • 4
  • 47
  • 84
0
#include <stdio.h>
#include <limits.h>

int main(void){
    unsigned  n;
    size_t size = CHAR_BIT * sizeof(n);
    char bits[size + 1];
    char *p = &bits[size];
    *p = '\0';
    printf("This program will help you find the equivalent binary-number to a given number \n");
    printf("Enter number :");
    scanf("%u", &n);
    if(n){
        for (; n ; n >>= 1)
            *--p = (n & 1) ? '1' : '0';
    } else {
        *--p = '0';
    }
    printf("The binary number to this number is(Read backwards) :");
    printf("%s\n", p);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70