With integer values a Right-Shift is equivalent to dividing by two. So you can create your binary representation simply by shifting right and evaluating whether the resulting bit in memory is 1 or 0 and outputting the appropriate character, either '1' or '0'. A simple function for that would be:
/** unpadded binary representation of 'v'. */
void binprn (const unsigned long v)
{
if (!v) {
putchar ('0');
return;
};
size_t sz = sizeof v * CHAR_BIT; /* get total bits in type */
unsigned long rem = 0;
while (sz--) /* loop sz number of times */
if ((rem = v >> sz)) /* while digits remain */
putchar ((rem & 1) ? '1' : '0'); /* output '1' or '0' */
/* note: the caller is responsible for adding the '\n' */
}
Then combining with your main() and adding validation of the input, you could do:
#include <stdio.h>
#include <limits.h>
/** unpadded binary representation of 'v'. */
void binprn (const unsigned long v)
{
if (!v) {
putchar ('0');
return;
};
size_t sz = sizeof v * CHAR_BIT; /* get total bits in type */
unsigned long rem = 0;
while (sz--) /* loop sz number of times */
if ((rem = v >> sz)) /* while digits remain */
putchar ((rem & 1) ? '1' : '0'); /* output '1' or '0' */
/* note: the caller is responsible for adding the '\n' */
}
int main (void) {
int x;
fputs ("enter x: ", stdout); /* prompt for integer */
if (scanf ("%d", &x) != 1) { /* read/validate user-input */
fputs ("error: invalid integer.\n", stderr);
return 1;
}
binprn (x); /* output binary represntation of x */
putchar ('\n'); /* tidy up with newline */
}
(note: the caller is responsible for newline control. There may be cases where you want to output several binary representations of numbers together before outputting the '\n' so that task is left for the calling function to carry out)
Example Use/Output
$ ./bin/binprn
enter x: 255
11111111
or
$ ./bin/binprn
enter x: 127
1111111
or
$ ./bin/binprn
enter x: 43690
1010101010101010
You can also adjust the logic to output a padded representation to X number of bits (4, 8, 16, 32, 64, etc...)
Look things over and let me know if you have further questions.
outputis an array of a single character, which is the null byte. That means you have no room to store anything else in it. Thestrncatcalls are writing past the end of array, resulting in undefined behavior.strncatrequires a string, not a char.